Reputation: 15118
I create a button:
var removeButton = document.createElement('button');
$(removeButton).attr('class', 'removeProduct');
$(removeButton).append(document.createTextNode('X'));
$(removeButton).data('divId', 'productLine' + numProductsInCart);
This works, the button appears.
However, when I try to produce an alert on that button being clicked it doesn't work. I click the button and it doesn't do anything.
Here is what I have got to so far:
$('.removeProduct').click(function() {
alert("Hey");
});
Upvotes: 0
Views: 331
Reputation: 624
Are you trying to add the click handler before appending the button on screen? This code works for me:
// Append the button
$("body").append(removeButton);
// Now add the handler
$('.removeProduct').on("click", function() {
alert("Hey");
});
Or you can add the handler on the button, before appending:
$(removeButton).on("click", function() {
alert("Hey");
});
So now, let's refactor the code a little:
function clickHandler(e) {
alert("Hey");
}
var removeButton = $("<button/>")
.html("X")
.addClass('removeProduct')
.data('divId', 'productLine' + numProductsInCart)
.on("click", clickHandler);
$("body").append(removeButton);
Hope it helps!
Upvotes: 0
Reputation: 166041
I am assuming you are attempting to bind the event handler before your add your button to the DOM. If that's the case, you need to delegate the event handler higher up the DOM tree:
$("#someAncestorElement").on("click", ".removeProduct", function() {
alert("Hey");
});
This works because DOM events tend to bubble up the tree from the element at which they originate. You can capture the event at any ancestor element. The on
method will check whether the event target matches the selector, and run the event handler if so. Note that if you're using a version of jQuery below 1.7 you will need to use delegate
instead of on
.
Alternatively, you could bind the event handler after you've created the element:
$(removeButton).on("click", function() {
alert("Hey");
});
Upvotes: 4
Reputation: 144729
try on
method:
$('<button>X</button>').addClass('removeProduct').attr('data-Id', 'productLine' + numProductsInCart).appendTo('div');
$('.removeProduct').on('click', function() {
alert("Hey");
});
Upvotes: 0
Reputation: 18483
Make sure that the first bit of code has been run before the second. Otherwise, it has not updated the class of the button to be removeProduct
and has nothing to bind to.
$(document).ready(function(){
$('.removeProduct').click(function() {
alert("Hey");
});
});
Upvotes: 0
Reputation: 43208
You might be trying to select the button ($('.removeProduct')
) before you have added it to the document (I don't see in your sample code where you're adding it to the document). Can't you use your existing removeButton
reference when you add the onclick
handler?
Upvotes: 0
Reputation: 3502
Try this
$(document).ready(function(){
$('.removeProduct').live("click", function() {
alert("Hey");
});
});
Upvotes: 0