0

I am new to JQuery and I'm trying to write code that changes a clicked button both in text and function. Here is the code:

$('.button1').click(
    function() {
        $(this).val('Button2');
        $(this).removeClass('button1').addClass('button2');
    }
);

$('.button2').click(
    function() {
        alert('Button 2 Clicked');
    }
);

The problem is, the second event does not fire and call the alert.

Thanks in advance

Flashheart
  • 103
  • 1
  • 8
  • 1
    you need to use .on(); – David Chase Aug 12 '13 at 21:24
  • 1
    The duplicate I posted isn't an exact duplicate, but the solution is the same. Event handlers are bound to _elements_, and changing the class of an element doesn't change the binding. In your case, you need to use event delegation. See the link. – Jason P Aug 12 '13 at 21:25
  • If you just want to click the 2nd button, you can add this line to the first function: `$('.button2').click();` – Ringo Aug 12 '13 at 21:30

1 Answers1

2

Event handlers are bound to elements, and changing the class of an element doesn't change the binding. In your case, you need to use event delegation.

From jQuery 1.7 onward, use .on() for that:

$(document).on('click', '.button1', 
    function() {
        $(this).val('Button2');
        $(this).removeClass('button1').addClass('button2');
    }
);

$(document).on('click', '.button2', 
    function() {
        alert('Button 2 Clicked');
    }
);

If those have a common ancestor, (say a <div id="container">) it could be used instead of document: $('#container').on('click', '.button2', .... It will work as long as every .button1 and .button2 you want the click event are under that div.

acdcjunior
  • 132,397
  • 37
  • 331
  • 304