Search code examples
javascriptjqueryhtmljquery-uitag-it

I am trying to add multiple tagit fields dynamically but it is not working for me


I have created a button to add new fields and the field I want to add is a tagit field on button click the data is apenned perfectly but the tagit feature is not working it is adding as blank ul. I do not know why it is not converting ul to a tagit field. Is there a way I can add tagit field dynamically?

I searched a lot on Google but nothing was found.

var i = 1;
$('.tagWritting').each(function() {
  $(this).tagit({
    options: {
      fieldName: 'test_name' + i,
    }
  });
  i++;
});
$('.addField').on('click', function() {
  $('.tags').append('<ul class="tagWritting"></ul>');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://rawgit.com/aehlke/tag-it/master/js/tag-it.js"></script>
<link href="http://aehlke.github.io/tag-it/css/jquery.tagit.css"rel="stylesheet" />
<a class="addField">Add New Field</a>
<div class="tags">
  <ul class="tagWritting"></ul>
  <ul class="tagWritting"></ul>
  <ul class="tagWritting"></ul>
</div>


Solution

  • The problem is the tag is been created, appended and you are not running the $().tagit() to this new element

    this part:

    $('.tagWritting').each(function() {...});  
    

    needs to run after each Tag append

    Or, after including a Tag, you can pick the last tag and do:

    $(tagElement).tagit({...});
    

    Something like:

    var i = 0;
    function addTagit(element){
      $(element).tagit({
        options: {
          fieldName: 'test_name' + i,
        }
      });
      i++;
    }
    
    $('.tagWritting').each(function(){
      addTagit(this);
    });
    
    $('.addField').on('click', function() {
      var tag = $('<ul class="tagWritting"></ul>');
      $('.tags').append(tag);
      addTagit(tag);
    });
    

    I didn't test the code, and I don't work with jQuery for years... but I think it can help you