RSM
RSM

Reputation: 15108

Alert text when submit detected

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.

Upvotes: 0

Views: 95

Answers (3)

ThiefMaster
ThiefMaster

Reputation: 318468

You have a syntax error, instead of $(#addToCart) you need $('#addToCart').

Besides that, you need to bind the submit event to the form, not the submit button (you'd bind click to 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 a click event to the button.

If you need to bind the event before the button exists, use a delegate. #container should be an element that already exists and is a parent of the button:

$('#container').on('click', '#addToCart', function() { ... });

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 .addToCart accordingly.

Upvotes: 5

madeye
madeye

Reputation: 1406

You have a syntax error. Try $('#addToCart').

Upvotes: 0

Murtaza
Murtaza

Reputation: 3065

please try the following code

function addToCart()
{
    $("#addToCart").live("submit", (function() {
        alert('Submit Detected.');
    });
}

Note: i have tried the same but since you have added the element at runtime you need to bind the event to the element.

Upvotes: -1

Related Questions