问题
I use jQuery autocomplete and have multiple input fields with different IDs, and they are populated from a MySQL database.
$("#CCU1").autocomplete({
minLength : 1,
source: function( request, response ) {
$.ajax({
url:"<?php echo site_url().'gsimc/autocomplete'; ?>",
dataType: 'json',
data: {
term : $("#CCU1").val(),
column: 'course',
tbl : 'tbl_courses'
},
success: function(data){
if(data.response == 'true') {
response(data.message);
}
}
});
}
});
The input fields has IDs of CCU1...CCU5, name='course'. Any idea how to autocomplete the five input fields instead of hardcoding each one?
Course1: <input type='text' name='course[]' id='CCU1'/><br />
Course2: <input type='text' name='course[]' id='CCU2'/><br />
Course3: <input type='text' name='course[]' id='CCU3'/><br />
Course4: <input type='text' name='course[]' id='CCU4'/><br />
Course5: <input type='text' name='course[]' id='CCU5'/><br />
回答1:
Assuming that your above code is working for one of them, you could do:
$("[id^=CCU]").each(function(){
$(this).autocomplete({
minLength : 1,
source: function( request, response ) {
$.ajax({
url:"<?php echo site_url().'gsimc/autocomplete'; ?>",
dataType: 'json',
data: {
term : $(this).val(),
column: 'course',
tbl : 'tbl_courses'
},
success: function(data){
if(data.response == 'true') {
response(data.message);
}
}
});
}
});
});
回答2:
Use $(this)
instead of hardcoding the ID:
term: $("#CCU1").val(),
Replace it with:
term: $(this).val(),
Full code:
$("[id^=CCU]").each(function(){
$(this).autocomplete({
minLength : 1,
source: function( request, response ) {
$.ajax({
url:"<?php echo site_url().'gsimc/autocomplete'; ?>",
dataType: 'json',
data: {
term : $(this).val(),
column: 'course',
tbl : 'tbl_courses'
},
success: function(data){
if(data.response == 'true') {
response(data.message);
}
}
});
}
});
});
来源:https://stackoverflow.com/questions/14013233/jquery-multiple-autocomplete-with-different-input-ids