0

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.

Tester
  • 798
  • 2
  • 12
  • 32
  • if you make the not working one use just the class like the one that is working, does that work? `.close` instead of `a.close`? – gmaniac Mar 22 '16 at 14:01
  • not working for that way too. – Tester Mar 22 '16 at 14:13
  • your fiddle works for me, if I add a color then click submit it shows that I added the color and if I click the `x` on that color and then click the submit it is removed and displays the correct colors. – gmaniac Mar 22 '16 at 15:10

1 Answers1

0

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();
})
Greg
  • 826
  • 5
  • 21