Reputation: 3
I need to create "button 02" by clicking on "Button 01", after that create "button 03" by clicking on "Button 02"
I tried with follow codes
$(document).ready(function(){
$(".btnone").click(function(){
var btntwostr= '<button type="button" class="btn btn-warning btntwo" >Button 02</button>';
$("#btntwodiv").html(btntwostr);
});
$(".btntwo").click(function(){
var btnthreestr= '<button type="button" class="btn btn-warning btnttree" >Button 02</button>';
$("#btnthreediv").html(btnthreestr);
});
});
<button type="button" class="btn btn-warning btnone" >Button 01</button>
<div id="btntwodiv"></div>
<div id="btnthreediv"></div>
first step is OK, but second step doesn't work, Please help to solve this problem.
Upvotes: 0
Views: 54
Reputation: 10045
You problem is that you bind to an element that doesn't exist yet, so you can either do as @PeteTNT suggests, or use the jquery .on handler, this helps you bind to elements that does't yet exist.
$(document).ready(function(){
$(".btnone").click(function(){
var btntwostr= '<button type="button" class="btn btn-warning btntwo" >Button 02</button>';
$("#btntwodiv").html(btntwostr);
});
$(document).on('click', ".btntwo", function(){
var btnthreestr= '<button type="button" class="btn btn-warning btnttree" >Button 02</button>';
$("#btnthreediv").html(btnthreestr);
});
});
Do note that there are alot of ways you can achieve this functionality in a more scalable way. And I will suggest you look into refactoring that code.
Upvotes: 2