1

I'm trying to target an element by a class name that I've added to it in jQuery. This seems to work fine if I add a new element, but I can't get the new events to bind to an element that was already in the DOM, but has been changed.

What am I doing wrong?

$(document).ready(function(){  
$(".activateRow").on("click",function(){
     $(this).text('Deactivate').addClass('deactivateRow btn-danger').removeClass('activateRow btn-success');
     $(this).parent().parent().removeClass('inactiveRow');
 });

$(".deactivateRow").on("click",function(){
    $(this).text('Activate').removeClass('deactivateRow btn-danger').addClass('activateRow btn-success');
    $(this).parent().parent().addClass('inactiveRow');
});

 })
Tamil Selvan C
  • 19,913
  • 12
  • 49
  • 70
erfling
  • 384
  • 2
  • 16

2 Answers2

5

To bind to new elements use delegation :

$(document.body).on("click", ".deactivateRow", function(){
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
1

Your code seems a little messy, I suggest you use the data api, your elements can have attributes set with data-nameOfYourAttribute='Value'. You can use this in jquery like this: //This is a getter/setter $('#myElement').data('nameOfYoutAttribute')

And for your problem you can do:

$('.myRows').on('click', function() {
    if($(this).data('activated') == false) {
       //Do stuff
       $(this).data('activated', true);
    } else {
       //Do stuff
       $(this).data('activated', false);
    };
});

Hope it helps

Nickydonna
  • 802
  • 1
  • 5
  • 18