Salem Albadawi
Salem Albadawi

Reputation: 3

how to add a button as html to a div and add click function

In the following code the button "alt2" shows up but does not alert "hi"

Is this the proper way to add a button?

<body>
<div id="test"></div><br>
<button id="add">add</button><br>
<button id='alt'>alt1</button>
<script type="text/javascript" >
$(function(){
    $("#add").click(function(){
        $("#test").html("<button id='alt2'>alt2</button>");     
    });
    $("#alt").click(function(){
        alert("hi");

    }); 

});

</script>

Upvotes: 0

Views: 192

Answers (2)

user6051866
user6051866

Reputation:

on("click")... for the second alt2 is missing. also i would suggest you use on("click")... instead of .("click") . .("click") this one may miss to fire the second time

<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<div id="test"></div><br>
<button id="add">add</button><br>
<button id='alt'>alt1</button>
<script type="text/javascript" >
$(function(){
	
	$(document).on("click", "#add", function(e) {
		e.preventDefault();
    
        $("#test").html("<button id='alt2'>alt2</button>");     
    });
	
	
	$(document).on("click", "#alt", function(e) {
		e.preventDefault();
    
        alert("hi 1");

    }); 	
	
	$(document).on("click", "#alt2", function(e) {
		e.preventDefault();
    
        alert("hi 2");

    }); 

});

</script>
</body>

Upvotes: 2

guradio
guradio

Reputation: 15565

$("#add").click(function() {
  $("#test").html("<button id='alt2'>alt2</button>");
});
$("#alt").click(function() {
  alert("hi");

});

$(document).on('click',"#alt2",function() { // use .on()
  alert("hi 2");

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="test"></div>
<br>
<button id="add">add</button>
<br>
<button id='alt'>alt1</button>

Use .on() for dynamically added elements.

Description: Attach an event handler function for one or more events to the selected elements.

Upvotes: 2

Related Questions