Enabling jQuery Autocomplete on dynamically created input fields
Asked Answered
N

6

7

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 a website that contains one input element. I've managed to get jQuery Autocomplete working nicely on this. The problem is that when i dynamically add additional elements using the .append method, these new elements do not work with autocomplete.

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

see jsfiddle for full code sample

Thankyou in advance for your help!! :) -Dean

Newsreel answered 22/10, 2014 at 0:33 Comment(1)
Thanks to everyone that commented. Some very well presented solutions.Newsreel
G
10

You must bind autocomplete after adding new elements

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

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

Gazelle answered 22/10, 2014 at 0:43 Comment(3)
Hello @dfionov, can you check this once #33411324 pls. ThanksClaiborn
what if we want to fetch data as we type in in the inpute box and data supplied there ?Silicon
Has anyone managed to do this with mdb5 autocomplete?Gram
F
5

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

Franklinfranklinite answered 21/10, 2016 at 1:59 Comment(2)
This is much easier and more generic solution that the other solutions.Dorladorlisa
This is great, but got a problem during on blur, I am getting this error cannot call methods on autocomplete prior to initialization; attempted to call method 'destroy'. How should I fix this thanks.Rockie
S
3

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
 });    
Spindlelegs answered 22/10, 2014 at 0:41 Comment(0)
H
2

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
}));
Hydrolyte answered 22/10, 2014 at 0:43 Comment(0)
E
0

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
      }
    });
  }
 });
});
Eva answered 10/7, 2020 at 19:22 Comment(0)
M
0
<script>
    $(document).ready(function() {
        
        var nhlTeams = ['Atlanta', 'Boston', 'Buffalo', 'Calgary', 'Carolina', 'Chicago', 'Colorado', 'Columbus', 'Dallas', 'Detroit', 'Edmonton', 'Florida', 'Los Angeles', 'Minnesota', 'Montreal', 'Nashville', ];
        var nbaTeams = ['New Jersey', 'New Rork', 'New York', 'Ottawa', 'Philadelphia', 'Phoenix', 'Pittsburgh', 'Saint Louis', 'San Jose', 'Tampa Bay', 'Toronto Maple', 'Vancouver', 'Washington'];
        var nhl = $.map(nhlTeams, function (team) { return { value: team, data: { category: 'Section A' }}; });
        var nba = $.map(nbaTeams, function (team) { return { value: team, data: { category: 'Section B' } }; });
        var teams = nhl.concat(nba);

        // Initialize autocomplete with local lookup:
        $('body').on('focus', '.db_items', function(){
            $(this).autocomplete({
                lookup: teams,
                minChars: 1,
                onSelect: function (suggestion) {
                    $('#selection').html('You selected: ' + suggestion.value);
                },
                showNoSuggestionNotice: true,
                noSuggestionNotice: 'Sorry, no matching results',
                groupBy: 'category'
            });
        });

    });
</script>
Messick answered 30/1, 2022 at 5:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.