Garrett Garrett - 1 month ago 6
HTML Question

How to stop tags being added to an array once limit is reached?

I’ve tried setting a limit on the amount of tag’s I can insert into the box using:

tagLimit: 2,


Although this stops you entering more than 2 into the box, it still adds them to the ‘sampleTags’ array. Would anyone know how to prevent it adding to the array once the limits reached?

JSFiddle: http://jsfiddle.net/uVxXg/137/

Answer

You can use the afterTagAdded event provided by tagit and move your code pushing the values into the array there. This way your code will only be executed when a tag is really added:

Your Code

  // When the user clicks submit
  $('form').submit(function(e) {
    var inp = $('#tagInput').val();
    $('#tagInput').val('');
    $('#tags').tagit('createTag', inp);
    sampleTags.push(inp);
    e.preventDefault();
  });

Remove the line with "sampleTags.push(inp);"

Add the following code to tagit function (see afterTagAdded event):

// When the user clicks submit
  $('#tags').tagit({
    availableTags: sampleTags,
    tagLimit: 2,
    afterTagRemoved: function(evt, ui) {
        console.log(ui.tagLabel)
      for(var i = 0; i < sampleTags.length; i++) {
        if (sampleTags[i] == ui.tagLabel) {
          sampleTags.splice(i, 1);
        }
      }
    },
    afterTagAdded: function(evt, data){
        sampleTags.push(data.tagLabel);
    }
  });

See working example here: http://jsfiddle.net/uVxXg/142/

Comments