Reputation: 47
I don't know why the jQuery click event on #btn
doesn't work.
`//this is the script`
$('document').ready(function(){
$('#btn').click(function(){
alert('2');
});
});
function appendToPopUp(){
document.getElementById('popUp').innerHTML='<BUTTON id="btn" onClick="alert(1)">clickerIci</BUTTON>';
}
<!--this is the body-->
<DIV id='popUp'></DIV>
<BUTTON onClick='appendToPopUp()'>display</BUTTON>
Upvotes: 0
Views: 699
Reputation: 24375
There are a couple of problems here:
$('document').ready(...
should be:
$(document).ready(...
Then you dynamically insert the btn
button. Since it's not available at document.ready
the event is not attached to it at all. You'll have to reattach the event inside appendToPopUp
.
function appendToPopUp()
{
document.getElementById('popUp').innerHTML='<BUTTON id="btn" onClick="alert(1)">clickerIci</BUTTON>';
$('#btn').click(function(){
alert('2');
});
}
So, in this case, you actually don't need $(document).ready()
.
Edit
What I'd actually do is something like this:
<DIV id='popUp'></DIV>
<BUTTON id="display">display</BUTTON>
$(document).ready(function() {
$('#display').on('click', function() {
$('#popUp').html('<BUTTON id="btn">clickerIci</BUTTON>');
$('#btn').on('click', function() {
alert('2');
});
});
});
See JSFiddle.
Upvotes: 4
Reputation: 516
Try with the below HTML...
On page load Jquery doesn't know about #btn so it will not bind the events so we explitcly calling the bindevents function after it is loaded to DOM.
<script>
function bindevents(){
$('#btn').on("click",function(){
alert('2');
});
}
function appendToPopUp()
{
document.getElementById('popUp').innerHTML='<BUTTON id="btn" onClick="alert(1)">clickerIci</BUTTON>';
bindevents();
}
</script>
<DIV id='popUp'></DIV>
<BUTTON onClick='appendToPopUp()'>display</BUTTON>
Upvotes: 0