skip to Main Content

I have a table and buttons and all buttons are getting generated with a loop.

<button type="button" class="btn btn-danger btn-sm remove-connetion" name="button">
<i class="fa fa-trash"></i>
</button>

I want to find which button I click and then change its class.

now in my jquery script

$( document ).on( 'click', '.remove-connetion', function (e) {
    e.preventDefault();
 $('td').find('.fa fa-trash').closest('button').removeClass('btn-danger');
 $('td').find('.fa fa-trash').closest('button').addClass('btn-secondary');

});

it’s not changing class.
Thanks for all help

2

Answers


  1. Use this instead inside the callback to get the current clicked button:

    $(document).on('click', '.remove-connetion', function(e) {
      e.preventDefault();
      var clicked = $(this);
      setTimeout( function() {
         clicked.removeClass('btn-danger');
         clicked.addClass('btn-secondary');
      }, 1000);
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"/>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"/>
    
    
    <button type="button" class="btn btn-danger btn-sm remove-connetion" name="button">
       <i class="fa fa-trash"></i>
    </button>
    <button type="button" class="btn btn-danger btn-sm remove-connetion" name="button">
       <i class="fa fa-trash"></i>
    </button>
    <button type="button" class="btn btn-danger btn-sm remove-connetion" name="button">
       <i class="fa fa-trash"></i>
    </button>
    Login or Signup to reply.
  2. You can do it like this:

    $( document ).on( 'click', '.remove-connetion', function (e) {
      e.preventDefault();
      e.target.classList.remove('btn-danger');
      e.target.classList.add('btn-secondary');
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    <button type="button" class="btn btn-danger btn-sm remove-connetion" name="button">
    <i class="fa fa-trash"></i>
    </button>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search