How can I create combination of tags with dynamic bootstrap tags input?

58 views Asked by At

I have one bootstrap tags input given on the page and there is an option to create dynamic bootstrap tags input where we can add multiple tags.

When any tag (e.g. Black) is added in first input (static input which is already given), a table row is created having that tag appended in first column. When we create a dynamic input and add a tag (e.g. 26) in the same, it will create a combination of both the tags(Black 26) and append it to the row.

Currently, I have added only two tags input and worked according to them. But there is a need to add multiple dynamic inputs and when we remove any tag from the input, it should also get removed from the row.

I have tried using the below code:

Html

<input type="text" name="attr[0][tags]" class="form-control tag-1" data-role="tagsinput" />

<input type="text" name="attr[1][tags]" class="form-control tag-2" data-role="tagsinput" />

jQuery

var inp1 = [];
      var inp2 = [];

      $(document).on('itemAdded', '.tag-1', function(e) {
        var tagInput = e.item;
        var tag = tagInput;
        if (tag !== '') {
          createRows(tag);
          inp1.push(tag);
        }
      });

      $(document).on('itemAdded', '.tag-2', function(e) {
        var tagInput = e.item;
        var tag = tagInput;
        if (tag !== '') {
          inp2.push(tag);
          var combinations = getAllTagCombinations(inp1, inp2);
          updateTable(combinations);
        }
      });

      // Create table row
      function createRows(tag) {

        var html = '<tr>'+
        '<td>'+tag+'</td>'+
        '</tr>';

        $('.tbl-body').append(html);
      }

      // Get all combinations of tags
      function getAllTagCombinations(tags1, tags2, tagsDynamic = []) {
        var combinations = [];
        $.each(tags1, function(index1, tag1) {
          if (tags2.length > 0) {
            $.each(tags2, function(index2, tag2) {
              var combination = tag1 + ' ' + tag2;
              combinations.push(combination);
            });
          } else {
            combinations.push(tag1);
          }
        });

        if (tagsDynamic.length > 0) {
          var cmb = [];
          $.each(combinations, function(index, combination) {
            $.each(tagsDynamic, function(indexDynamic, tagDynamic) {
              var updatedCombination = combination + ' ' + tagDynamic;
              cmb.push(updatedCombination);
            });
          });
          return cmb;
        }

        return combinations;
      }

      // Update tag table
      function updateTable(combinations) {

        $.each(combinations, function(index, combination) {
            createRows(combination);
        });
      }
0

There are 0 answers