Devin Dixon
Devin Dixon

Reputation: 12383

How to find which button was used on the submit

I am trying to distinguish which button/link was pressed on the submit. I am generating a product to purchase like so:

var product = JSON.parse(data);

var html = '';
html += '<div>'
html += '<form class="buy-product" >';
html += '<div class="product_title">Price</div>'
html += '<div class= "product_info_2" >' + product['product_price'] + '</div>'
html += '<div class= "product_info_2" >' + product['product_description'] + '</div>'
html += '<div class="product_title">Image</div>'
html += '<div class= "product_info_2" >Coming Soon</div>'
html += '<input type="hidden" name="product_id" value="' + product['product_id'] + '" id="product_id" >'
html += '<a href="#" class="button rightButton submit" id="add-to-cart-button" style="margin-right:100px;" >Add To Cart!</a>'
html += '<a href="#" class="button rightButton submit" id="view-product-button" >Buy It Now!</a>'
html += '</form>'
html += '</div>'

$('#product .toolbar h1').html(product['product_name']);
$('#view-product').html(html);​

And I am getting that the product was submitted like this:

$('#product').on('submit', '.buy-product', function() {
    var product_id = $(this).children('input[name=product_id]').val();
    createPurchaseView(product_id);
    jQT.goTo('#purchase');
});​

But how can I distinguish between the 'Add To Cart' vs the 'Buy Now' being pressed?

Upvotes: 2

Views: 393

Answers (2)

Dave
Dave

Reputation: 2417

Add the event argument to your callback and check its target property.

$('#product').on('click', '.buy-product', function(event) {
    var $target = $(event.target);
    if($target.is("#add-to-cart-button") {
        //Add to cart
    } else if($target.is("#view-product-button") {
        //Buy it now
    }
});

jQuery event.target page

Upvotes: 5

TimCodes.NET
TimCodes.NET

Reputation: 4699

Add click handlers to the buttons in which you add some data to the element that was clicked eg:

$('.button').click(function(){
 $(this).data("clicked", true);
});

Then check for this data in the submit event:

$('.button').each(function(){
 if ($(this).data("clicked")) alert("it was me");
});

Upvotes: 0

Related Questions