jQuery具有不同输入ID的多个自动完成
我使用jQuery自动完成并具有多个具有不同ID的输入字段,并且它们是从MySQL数据库填充的。
$("#CCU1").autocomplete({ minLength : 1, source: function( request, response ) { $.ajax({ url:"", dataType: 'json', data: { term : $("#CCU1").val(), column: 'course', tbl : 'tbl_courses' }, success: function(data){ if(data.response == 'true') { response(data.message); } } }); } });
输入字段的ID为CCU1 … CCU5,name =’course’。 知道如何自动完成五个输入字段而不是硬编码每个字段吗?
Course1:
Course2:
Course3:
Course4:
Course5:
假设您的上述代码适用于其中一个代码,您可以执行以下操作:
$("[id^=CCU]").each(function(){ $(this).autocomplete({ minLength : 1, source: function( request, response ) { $.ajax({ url:"", dataType: 'json', data: { term : $(this).val(), column: 'course', tbl : 'tbl_courses' }, success: function(data){ if(data.response == 'true') { response(data.message); } } }); } }); });
使用$(this)
而不是硬编码ID:
term: $("#CCU1").val(),
替换为:
term: $(this).val(),
完整代码:
$("[id^=CCU]").each(function(){ $(this).autocomplete({ minLength : 1, source: function( request, response ) { $.ajax({ url:"", dataType: 'json', data: { term : $(this).val(), column: 'course', tbl : 'tbl_courses' }, success: function(data){ if(data.response == 'true') { response(data.message); } } }); } }); });