Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to prevent default select event in autocomplete jquery

The jQuery Autocomplete docs for the select( event, ui ) option say:

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.

Cancelling this event prevents the value from being updated, but does not prevent the menu from closing.

So how do I cancel the event? Here's my code.

$("#txt1").autocomplete({
    minLength: 1,
    source:  "abc.php",
    select: function(event, ui) 
    {
        event.preventDefault();
        //alert("Select");
        var label= ui.item.label;
        var value= ui.item.value;
        $('#txt1').val(ui.item.label);
    }
});
like image 948
Someone Avatar asked Aug 03 '10 21:08

Someone


1 Answers

I know this is a very old question, but I just came across the problem myself. The answer for me is to put event.preventDefault(); at the end of the select method like this:

$("#txt1").autocomplete({
    minLength: 1,
    source:  "abc.php",
    select: function(event, ui) 
    {
        //alert("Select");
        var label= ui.item.label;
        var value= ui.item.value;
        $('#txt1').val(ui.item.label);
        event.preventDefault();  // <---- I moved!
    }
});

For me, if event.preventDefault(); is put at the start of the function, then the default event doesn't fire and the rest of the function doesn't execute. If it's moved to the end, then it works as expected. Hope this helps someone else.

like image 68
Michael Avatar answered Sep 28 '22 08:09

Michael