how to prevent default select event in autocomplete jquery
Asked Answered
P

3

8

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);
    }
});
Premonitory answered 3/8, 2010 at 21:44 Comment(0)
A
10

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.

Aflutter answered 19/7, 2013 at 23:34 Comment(0)
A
0

So this is a bit of a hack that worked for me: In my case selecting an entry in the pulldown (either by mouse click or using arrow keys to highlight and hitting ENTER), I was using the value to construct a URL and then sending the browser to it but it still got copied into the search box. None of the answers I tried worked to prevent that. So to stop value being displayed in the search box, I made the value the same as label in my JSON and added an extra field code that my select event handler uses to construct the URL I need:

$( "#autocomplete" ).autocomplete({
  source: "http://www.example.com/search",
  minlength: 2,
  select: function( event, ui ) {
    // go to page on ENTER
    window.location.href = "/page/" + ui.item.code;
  }
});
Ackerman answered 11/2, 2017 at 21:42 Comment(0)
E
-1

using this parameter selectFirst: false

Excommunication answered 7/9, 2010 at 3:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.