Don Don - 7 months ago 9
Javascript Question

Tokenfield for Bootstrap can not get "click" event when delete a token

I want to get "click" event when i want to delete a token using Tokenfield for Bootstrap. I only can get "click" event for existing token but not dynamically generated one.

// working for existing token
$('.close').on('click', function(){
alert('OK!');
});

// not working
$(document).on('click', 'a.close', function(){
alert('delete');
});


Please see this jsfiddle for details.

Answer

Its normal, you create a new element of dom. But your $('.close') is already initialized.

So you can try to do something like that:

See jsfiddle http://jsfiddle.net/rns3hang/14/

$(document).ready(function() {   
    $('#tokenfield').tokenfield({
      autocomplete: {
        source: ['red','blue','green','yellow','violet','brown','purple','black','white'],
        delay: 100
      },
      showAutocompleteOnFocus: true
    });

    $("form").submit(function(e) {
        e.preventDefault();
        $('.form-data').text( $('#tokenfield').val());
    });
    close();


});

function close() {
    $('.close').on('click', function(){
                alert('OK!');
        });

    $(document).on('click', 'a.close', function(){
         alert('delete');
        });

}

$('input').change(function() {
close();
})