0

i make a simple example in jquery .In my example user can added multiple entries using add button. Example "one" ,"two" .There is 'X' text in each entry .I am binding click event on 'X' span . https://jsfiddle.net/kzcozeeg/1/

Issue event is bind multiple times why ? example add two entry "one" and "two" .click "X" on first entry (one) .it show console message two times why ?

$(function() {
    $('#btn').click(clickhandler)
    function clickhandler(params) {
        var user= $('.username').val();
        var str = '<div><span>'+user +'</span>  <span class="abc">X</span></div>' 
        $('#wrapper').append(str);
        $('.abc').on('click',function () { 
         console.log($(this).prev('span').text())
         })
    }
})

Thanks

user944513
  • 9,790
  • 23
  • 109
  • 225

1 Answers1

2

Delegate click event instead:

$(function() {
  $('#btn').click(clickhandler)

  function clickhandler(params) {
    var user = $('.username').val();
    var str = '<div><span>' + user + '</span>  <span class="abc">X</span></div>'
    $('#wrapper').append(str);

  }

  $('#wrapper').on('click', '.abc', function() {
    console.log($(this).prev('span').text())
  })
})

This way, you can handle click event on dynamic elements (because click event bubbles).

And your issue was because on each click on #btn, you were adding a new click event on each .abc elements, without removing any previously bound ones.

A. Wolff
  • 72,298
  • 9
  • 84
  • 139