0

Twitter bootstrap tokenfield

Is there a way to cancel the creation of a token inside .on('beforeCreateToken') if invalid input is detected?

davidkonrad
  • 83,997
  • 17
  • 205
  • 265
MikeAlike234
  • 759
  • 2
  • 12
  • 29

1 Answers1

0

Yes. I assume you are using this library -> http://sliptree.github.io/bootstrap-tokenfield/ ??

Just reset the token in the beforeCreateToken handler, here if the token about to be inserted is contained in a exclusion list :

var exclusionList = ['a','b','c'];

$('#tokenfield').on('beforeCreateToken', function(e) {
  var token = e.token.value;
  if (exclusionList.indexOf(token)>-1) {
    e.token=false;
  } 
});

If empty, the token is not being inserted (rather obvoius :)


From the source, about line 176-178 in latest development version v0.11.0 (https://github.com/sliptree/bootstrap-tokenfield/blob/master/js/bootstrap-tokenfield.js) :

  this.$element.trigger( beforeCreateEvent )

  if (!beforeCreateEvent.token) return

beforeCreateToken is triggered inside createToken(), if you set e.token to false or empty, the function is exited and

var token = $('<div class="token" />')
            .attr('data-value', value)
            .append('<span class="token-label" />')
            .append('<a href="#" class="close" tabindex="-1">&times;</a>')

is never reached. So this is actually thé way to cancel the creation.

davidkonrad
  • 83,997
  • 17
  • 205
  • 265
  • Thanks! That way a empty token is created. I want to abort the Creation. – MikeAlike234 Feb 23 '14 at 16:13
  • No. Nothing is created when it is empty. Alternatively, set e.token to false (as I have updated the answer) - using the latest downloadable version. Check the code for yourself, if you set the token to false (or empty) the creation is cancelled by return. – davidkonrad Feb 23 '14 at 16:48