Garrett Garrett - 1 year ago 55
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?


Answer Source

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();
    $('#tags').tagit('createTag', inp);

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

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

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

See working example here:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download