In a function called outputProducts I have added a submit button to my table:
$(addToCartCell).append("<input type='submit' id='addToCart' value='Add To Cart'>");
In order to check the submit button was pressed I make another function:
function addToCart()
{
$(#addToCart).submit(function() {
alert('Submit Detected.');
});
}
But this isn’t working and the table created in the function before doesnt even show up, but when I get rid of the addToCart function it does.
You have a syntax error, instead of
$(#addToCart)you need$('#addToCart').Besides that, you need to bind the
submitevent to the form, not the submit button (you’d bindclickto the button, but since you want to do something on submit, binding the submit event to the form is the way to go).If you do not have a form, use
type="button"since there’s nothing to submit anyway and bind aclickevent to the button.If you need to bind the event before the button exists, use a delegate.
#containershould be an element that already exists and is a parent of the button:And since you seem to have multiple products, remember that IDs have to be unique – so if you have more than one button, use a class instead and change the selector to
.addToCartaccordingly.