Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery UI autocomplete submit onclick result

I've been trying to figure out how to submit the form when the person selects the result from choices of the autocomplete. It needs to work with a mouse click or enter button. I see examples out there but always in pieces. No one shows the entire function.

I have this code below but I get errors saying result is not a function. I don't know how to combine this to do what I would like. Any help is appreciated.

jQuery(document).ready(function(){  

jQuery("#vsearch").autocomplete("ajax/search.php",
    {
    minLength: 2
}
);
jQuery("#vsearch").result(function(event, data, formatted) {
      jQuery('#vsearch').value( formatted );
      jQuery('#search').submit();
});
});
like image 692
Panama Jack Avatar asked Mar 20 '11 01:03

Panama Jack


2 Answers

From: http://api.jqueryui.com/autocomplete/#event-select

select - Type:autocompleteselect

Triggered when an item is selected from the menu; ui.item refers to the selected item. The default action of select is to replace the text field's value with the value of the selected item. Canceling this event prevents the value from being updated, but does not prevent the menu from closing.

Code examples

Supply a callback function to handle the select event as an init option.

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

Bind to the select event by type: autocompleteselect.

$( ".selector" ).bind( "autocompleteselect", function(event, ui) {
  ...
});

So you would use:

EDIT: (modified in case user does not select anything)

$("#vsearch").autocomplete({
    source: "ajax/search.php",
    minLength: 2,
    select: function(event, ui) {
        if(ui.item){
            $('#vsearch').val(ui.item.value);
        }
        $('#search').submit();
    }
});

If I am sure of what you are wanting to do.

like image 194
mattsven Avatar answered Oct 21 '22 04:10

mattsven


Actually, you don't need to target the for element and form by ID... since that information is already passed to the select function via the Event object. It's better to get the form this way because you may have multiple forms on a page that you want to apply autocomplete to. Or you may want autocomplete on multiple elements.

Also, the syntax in the other answer is wrong. JQuery uses .val() not .value() to set an input's value.

Here's a corrected example:

$("#vsearch").autocomplete({
    source: "ajax/search.php",
    minLength: 2,
    select: function(event, ui) {
        //assign value back to the form element
        if(ui.item){
            $(event.target).val(ui.item.value);
        }
        //submit the form
        $(event.target.form).submit();
    }
});
like image 28
Anthony McLin Avatar answered Oct 21 '22 04:10

Anthony McLin