I am designing a form where I need to input two individuals, both fields are backed by autocomplete from jquery-ui. The autocomplete actions are the same.
Here is the problem I am facing:
When actually inputing into the form, both fields will send out the correct AJAX request to fetch autocomplete candidates. But only the first form will output the result list correctly.
The selector I currently use is:
$(".person_input").autocomplete()
and changing the selector does not help:
$("#person1,#person2").autocomplete()
I would like to know if there are any way I can change the selector or some autocomplete behavior so I can apply autocomplete to both fields correctly without having to write the same functions twice in my code.
Thank you in advance,
The 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 the autcomplete 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 );
};
Iterate the dom ->
$(".person_input").each(function(){ //grab each element with the class = person_input
For each element found, run autocomplete()
$(this).autocomplete();
Modify autocomplete within the scope of this function to have it apply 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 );
};
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With