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();
});
});

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.


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();
    }
});

Need Your Help

Angular2 date pipe does not work in IE 11 and edge 13/14

datetime angular format pipe internet-explorer-11

I'm using Angular 2.0 final, and I have an incorrect format of dates when I add hours and minutes in the format string:

How to convert stream results to string

java dom filestream

I want to convert the stream result output to string since I want