Reputation: 4564
I can't make my button respond to clicks. I generated this button using html() method:
var button1 = '<button class="btn btn-default" id="button1">Back</button>';
$(".component").html(button1);
This button renders on the screen, but doesn't work, nothing happens when I click.
$("#button1 ").on('click',function(e){
console.log("clicked");
});
The same html code inserted by hand (hardcoded) works fine.
Upvotes: 0
Views: 293
Reputation: 223
You have some mistakes in your code.
You have a space after button1 here
$("#button1 ")
And you have ommited );
after onclick
function.
There is a code who run perfectly
var button1 = '<button id="button1">Back</button>';
$(".component").append(button1);
$("#button1").on('click', function() {
alert("clicked");
});
.component {
width: 200px;
height: 200px;
border: solid 2px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="component">
</div>
And it's better to use .append()
not .html()
because .html()
overwrite the whole html content of the container.
Upvotes: 0
Reputation: 318182
You probably need delegated event handlers, but in this case just creating the element with jQuery solves the issue and looks better.
var button1 = $('<button />', {
'class' : 'btn btn-default',
id : 'button1',
text : 'Back',
on : {
click : function() {
console.log('clicked');
}
}
});
$(".component").html(button1);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="component"></div>
Upvotes: 2
Reputation: 1232
That's because jquery binds your click event when your browser reads the page. When you dynamically insert your button, it has no event binded.
You should put the code that binds the click event after the code which inject the button. Or put the code about the click event in a function and call it whenever a newly injected button needs its click event to be handled.
Upvotes: 0
Reputation: 6565
You should delegate events to elements created after DOM was loaded.
$(document).on('click','#button1',function(e){
console.log("clicked");
}
Upvotes: 0