How to prevent default select event in jquery autocomplete

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

$("#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); } }); 
+7
jquery jquery-autocomplete
source share
3 answers

I know this is a very old question, but I myself ran into a problem. The answer for me is to put event.preventDefault(); at the end of the select method as follows:

 $("#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 placed at the beginning of the function, the event does not fire by default, and the rest of the function is not executed. If it moves to the end, then it works as expected. Hope this helps someone else.

+6
source share

So, this is a bit of a hack that worked for me: in my case, selecting an entry in the drop-down list (with a mouse click or using the arrow keys to highlight and press ENTER) I used the value construct to build the URL and then send the browser, but it still copied to the search field. None of the answers I tried interfered with this. Thus, to stop the value displayed in the search box, I made the value the same as the label in my JSON, and added an additional code field, which the select event handler uses to create 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; } }); 
0
source share

using this selectFirst parameter: false

-one
source share

All Articles