Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery UI autocomplete field not submitting when pressing enter

I'm following the Railscast on this topic, and although the autocomplete feature works, I am unable to get it to submit the form when the user selects an item and presses enter. I have this (coffeescript) code but it doesn't seem to work... can anyone see where I'm going wrong please?

jQuery ->
  $('#search_bar').autocomplete( 
    source: $('#search_bar').data('autocomplete-source')
  ).keydown (e) ->
    $('#search_button').trigger "submit" if e.keyCode is 13

Ideally I would like it to submit on selecting an item via a mouse click too - but not sure if that's possible?

Update: I've tried this...

jQuery ->
  $('#search_bar').autocomplete
    source: $('#search_bar').data('autocomplete-source'),
    select: (event, ui) ->
      $(this).parents("form").submit()

...and although it now works if you use the keyboard to select an item (and press enter), if you select an item via a mouse click it only sends the string that you had typed and not the complete word from the auto-complete drop-down. (I guess what I need is for the search field to be updated with the contents of the text on mouse-over?)

Update 2: Sorted! Just add this onto the end

focus: (event, ui) ->
   $('#search_bar').val(ui.item.value)
like image 407
A4J Avatar asked Dec 26 '22 19:12

A4J


2 Answers

Use the select event. documentation here The enter key is caught by autocomplete to close the menu and intentionally does not propagate. The select event will fire for both the enter key and mouse select. However when clicked the form will be submitted before the label has a chance to change, so have to set that value first. Depending on your data source you may want to use item.label instead of item.value.

$('#search_bar').autocomplete({
   source: $('#search_bar').data('autocomplete-source'),
   select: function(event, ui) {
         $(this).val(ui.item.value);
         $(this).parents("form").submit();  // this will submit the form.
   }
})

I believe the coffeescript would look like this

$('#search_bar').autocomplete(
   source: $('#search_bar').data('autocomplete-source'),
   select: (event, ui) ->
         $(this).val(ui.item.value).parents("form").submit();
)
like image 153
Nal Avatar answered Dec 29 '22 10:12

Nal


Don't know much about coffee script, but this is how I would do it in javascript

http://jqueryui.com/demos/autocomplete/

You can use the 'select' event. When the user selects something, do your submit:

$( ".selector" ).autocomplete({
    select: function(event, ui) {
        $('#theForm').submit();
    }
});

I am fairly certain this will take care of both cases for you. Both onEnter and onClick.

like image 33
jForrest Avatar answered Dec 29 '22 10:12

jForrest