0

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>
0

2 Answers 2

2

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>

Sign up to request clarification or add additional context in comments.

2 Comments

just a thought submit what? from Also added the e.preventDefault(); to prevent the button from doing something else such as submitting
@guradio using it or not using it in this context will have no harm. Just acting safe. But let me remove that something else
2

$("#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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.