Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
449 views
in Technique[技术] by (71.8m points)

javascript - AutoComplete in jQuery with dynamically added elements

My requirement is to show few options when user input some characters (minimum 3) in one of input field which might be added dynamically too.

I can not load data at page loading at beginning because data is huge. There is an ajax call to get that filtered data.

The issue what I am getting is Expected identifier error on page loading at line# 2. So, could you please tell what is wrong with the below code?

$(document).on('keydown.autocomplete', 'input.searchInput', function() {                
            source: function (request, response) { // Line # 2
            var id = this.element[0].id;

            var val = $("#"+id).val();             
            $.ajax({                     
                    type : 'Get',
                    url: 'getNames.html?name=' + val,
                    success: function(data) {
                        var id = $(this).attr('id');
                        $(this).removeClass('ui-autocomplete-loading'); 
                        response(data);
                    },error: function(data) {
                          $('#'+id).removeClass('ui-autocomplete-loading');  
                    }
                  });
              },
                minLength: 3
            });
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

How about using another approach: initialize the autocomplete when you create the input:

$(function() {

  // settings for each autocomplete
  var autocompleteOptions = {
    minLength: 3,
    source: function(request, response) {
      $.ajax({
        type: "GET",
        url: "getNames.html",
        data: { name: request.term },
        success: function(data) {
          response(data);
        }
      });
    }
  };

  // dynamically create an input and initialize autocomplete on it
  function addInput() {
    var $input = $("<input>", {
      name: "search",
      "class": "searchInput",
      maxlength: "20"
    });
    $input
      .appendTo("form#myForm")
      .focus()
      .autocomplete(autocompleteOptions);
  };

  // initialize autocomplete on first input
  $("input.searchInput").autocomplete(autocompleteOptions);
  $("input#addButton").click(addInput);
});
<form id="myForm" name="myForm" method="post">
  <input id="addButton" type="button" value="Add an input" />
  <input name="search" class="searchInput" maxlength="20" />
</form>

jsFiddle with AJAX


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...