Apply the same autocomplete action to multiple form fields?

I create a form in which I need to enter two people, both fields are supported by autocomplete from jquery-ui. Autocomplete actions are the same.

Here is the problem I am facing:

When you actually enter the form, both fields will send the correct AJAX request to select the autocomplete candidates. But only the first form displays the list of results correctly.

The selector used by me:

$(".person_input").autocomplete() 

and changing the selector doesn't help:

 $("#person1,#person2").autocomplete() 

I would like to know if there is a way to change the selector or some kind of autocomplete behavior, so I can correctly apply autocomplete to both fields without repeating the same functions in my code.

Thanks in advance,

Form fields are defined as such:

 <input type="text" value="" name="person1" class="person_input" id="person1"> <input type="text" value="" name="person2" class="person_input" id="person2"> 

and autocomplete code as such:

 $(".person_input").autocomplete({ source: function(request, response) { $.ajax({ url: "/ajax/get_person/", data: {'q':request.term}, dataType: "json", type: "POST", success: function(data){ response(data); }, }); }, focus: function( event, ui ) { $(this).val(ui.item.name); return false; }, select: function( event, ui ) { $(this).val(ui.item.name); return false; } }).data( "autocomplete" )._renderItem = function( ul, item ) { return $( "<li></li>" ) .data( "item.autocomplete", item ) .append( "<a>" + item.name + "</a>" ) .appendTo( ul ); }; 
+4
source share
2 answers

Iterate dom β†’

 $(".person_input").each(function(){ //grab each element with the class = person_input 

For each item found, run autocomplete ()

  $(this).autocomplete(); 

Change the autocomplete within this function so that it applies to all forms.

 $(".person_input").each(function(){ $(this).autocomplete({ source: function(request, response) { $.ajax({ url: "/ajax/get_person/", data: {'q':request.term}, dataType: "json", type: "POST", success: function(data){ response(data); }//unnecessary trailing comma removed here }); }, focus: function( event, ui ) { $(this).val(ui.item.name); return false; }, select: function( event, ui ) { $(this).val(ui.item.name); return false; } }).data( "autocomplete" )._renderItem = function( ul, item ) { return $( "<li></li>" ) .data( "item.autocomplete", item ) .append( "<a>" + item.name + "</a>" ) .appendTo( ul ); }; }); 
+15
source

Try this to make sure it isolates 2 instances:

 $(".person_input").each(function(){ $(this).autocomplete(/* options*/); }) 

EDIT: see trailing comma after success must be removed for IE

+2
source

Source: https://habr.com/ru/post/1400161/


All Articles