Enabling jQuery Autocomplete on dynamically created input fields

前端 未结 5 1025
鱼传尺愫
鱼传尺愫 2021-01-05 15:23

I\'ve read almost every article i could find on how to accomplish this, but i\'m still failing miserably. mostly because i\'m an amateur at jQuery/Javascript.

I have

相关标签:
5条回答
  • 2021-01-05 15:34

    I actually found that a more reliable way was to bind using 'on' with the 'focus' action to init the auto complete based on the field class and destory it on exit. This way it cleans up the garbage and only inits it once you need to.

    I was using it with cloning rows though and even doing deep cloning, which would clone the plus and minus buttons for the rows, it wasn't cloning the autocomplete.

    var auto_opts = {...opts...}
    
    $('body').on('focus', '.search_field', function(){
        $(this).autocomplete(auto_opts).on('blur', function(){$(this).autocomplete('destroy')});
        });
    

    It also means that you aren't forced into using the last row because it works on the field as you focus on it

    0 讨论(0)
  • 2021-01-05 15:37

    Here is the simpler way to use autocomplete for dynamically created input fields.

    $('body').on('focus', '.dynamic-input-class', function (e) {
     $(this).autocomplete({
      minLength: 2,
      delay: 500,
      source: function (request, response) {
       $.ajax( {
          url: "server side path that returns json data",
          data: { searchText: request.term},
          type: "POST",
          dataType: "json",
          success: function( data ) {
            $("#data-success").html(data.returnedData); //returnedData is json data return from server side response
          }
        });
      }
     });
    });
    
    0 讨论(0)
  • 2021-01-05 15:45

    You must bind autocomplete after adding new elements

    $(wrapper).find('input[type=text]:last').autocomplete({
                    source: availableAttributes
    }); 
    

    See example: http://jsfiddle.net/r08m8vvy/4/

    0 讨论(0)
  • 2021-01-05 15:47

    I Updated the fiddle http://jsfiddle.net/r08m8vvy/5/

    You have to bind the autocomplete for new element

    $(wrapper).append($('<div><input type="text" name="mytext[]"/><a href="#" class="remove_field">Remove</a></div>').find(":text").autocomplete({
        source: availableAttributes
    }));
    
    0 讨论(0)
  • 2021-01-05 15:55

    See http://jsfiddle.net/r08m8vvy/2/

    Give the new input an ID and call autocomplete on it. The initial autocompate call you make won't include the dynamically added inputs.

     $(wrapper).append('<div><input id="' + x + '" type="text" name="mytext"/><a href="#" class="remove_field">Remove</a></div>'); //add input box
    
     $( "input[id="+ x +"]" ).autocomplete({
         source: availableAttributes
     });    
    
    0 讨论(0)
提交回复
热议问题