jQuery multiple autocomplete with different input IDs

吃可爱长大的小学妹 提交于 2019-12-13 17:22:15

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!