0

I’m launching a bootstrap modal using a button and then changing the button class and text via jQuery. I want to launch another bootstrap modal once the button class is changed.

Here is my code

$('.btn myBtn1').click(function () {
   var id = $(this).closest('tr').data('id');
$('#myModal1').data('id', id).modal('show');
 $('. btn').addClass(' myBtn2');
$('. btn').removeClass(' myBtn1');

});
//second modal code
$('.btn myBtn2').click(function () {
  var id = $(this).closest('tr').data('id');
$('#myModal2').data('id', id).modal('show');
 $('. btn').addClass(' myBtn1');
$('. btn'). removeClass(' myBtn2');

});

My issue is its launching the same modal. Modal 1 and never loads the modal two. What should I do to fix this? Appreciate your time.

Jordyn
  • 1,133
  • 2
  • 13
  • 28
  • This `$('.btn myBtn2').click(...)` is called *before* the button has that class, at a time at which the selector doesn't match anything. –  Jan 13 '17 at 12:37

2 Answers2

1

You have changed button class dynamically so client event is not attached. In this case you have click event attached with parent instead of child. More info In jQuery, how to attach events to dynamic html elements?

Use this:

$('body').on('click', '.btn myBtn2', function () {
Community
  • 1
  • 1
Manwal
  • 23,450
  • 12
  • 63
  • 93
1

Change the following line of code:

//second modal code
$('.btn myBtn2').click(function () {

to

//second modal code
$(document).on('click', '.btn myBtn2', function(){

Reason: When you are changing the selectors dynamically than you have to make your event listeners also capable of handling that. $('selector').click(); works for static selectors only.

Mayank Pandeyz
  • 25,704
  • 4
  • 40
  • 59