0

I have a button which is added dynamically

    <button id="btnSubmit">Button 1</button>

    $(document).ready(function(){
    $('#btnSubmit').on('click', function(){
        alert('Button 1');
        var button2 = '<button id="btn2" >Button 2</button>';
        $('#btnSubmit').after('<p></p>' + button2);
    });

    $(document).on('#btn2', 'click', function(){
        alert('Button2 clicked');
    });
  });

Now, when I click on #btn2 the event is not detected. How can this be fixed?

user544079
  • 13,851
  • 35
  • 102
  • 160

2 Answers2

1

You are adding btn2 for every click of btnSubmit, this will create multiple buttons with same id and it is not acceptible with jQuery.

Use unique id or class for every dynamic button adde, and use .on() to bind click event to button, see below code

HTML

 <button id="btnSubmit">Button 1</button>

jQuery

$(document).ready(function(){
    $('#btnSubmit').on('click', function(){
        alert('Button 1');
        var button2 = '<button class="btn2" >Button 2</button>';
        $('#btnSubmit').after('<p></p>' + button2);
    });

    $(document).on('click','.btn2', function(){
        alert('Button2 clicked');
    });
  });
Bhushan Kawadkar
  • 27,451
  • 5
  • 33
  • 55
-1
$(document).ready(function(){
$('#btnSubmit').on('click', function(){
    alert('Button 1');
    var button2 = '<button id="btn2" >Button 2</button>';
    $('#btnSubmit').after('<p></p>' + button2);
    $(document).bind('#btn2', 'click', function(){
    alert('Button2 clicked');
    });
});
});

try this code It will work. or you can try this as well.

 $(document).ready(function(){
 $('#btnSubmit').on('click', function(){
    alert('Button 1');
    var button2 = '<button id="btn2" >Button 2</button>';
    $('#btnSubmit').after('<p></p>' + button2);
    $('#btn2').live('click', function(){
    alert('Button2 clicked');
    });
});
});