Search code examples
jqueryhtmltag-it

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/


Solution

  • 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/

    UPDATE:

    To answer the comment. Use "onTagLimitExceeded" to give feedback when tagLimit is reached. Working example here: http://jsfiddle.net/uVxXg/144/

        afterTagAdded: function(evt, data){
            sampleTags.push(data.tagLabel);
        },
        onTagLimitExceeded: function(evt, data){
            alert('Tag limit reached!');
        }
    

    You can find a list of all events on the tag-it github page here: https://github.com/aehlke/tag-it/blob/master/README.markdown