简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM