Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

in jquery, how can i reference current form from button click

Tags:

html

jquery

forms

I have a form below; I have changed the submit button to just type "Button" so I would be able to run some JavaScript before submitting the form:

Here is my form:

<form action="/Cart" method="post">
     <input type="hidden" name="name" value="12" />
     <input type="button" class="addToCartButton" value="Add to Cart" />
 </form>

Here is my initial event handler:

$(document).ready(function () {
    $('.addToCartButton').click(function () {

       //need to reference current form here
       //need to reference the hidden input with name="Name" above
    });
});

I have a number of these forms on the same page so I need to relatively reference the form and some other inputs inside that form. What is the best way to doing it? I was thinking about putting some prefix that would be unique to each form and then using that in the selector but that seems very hacky ...

like image 1000
leora Avatar asked Aug 22 '11 13:08

leora


People also ask

How do you know which submit button was clicked in jQuery?

activeElement will give you the submit button that was clicked. document. activeElement. getAttribute('value') will give you that button's value.

How do you check form is submitted or not in jQuery?

submit(function(e) { e. preventDefault(); $("#some-span"). html(data); });


2 Answers

This should work:

$(document).ready(function () {
    $('.addToCartButton').click(function () {

       //need to reference current form here
       $(this).closest('form');
       //need to reference the hidden input with name="Name" above
       $(this).closest('form').find('input[name="name"]');
    });
});
like image 84
David Thomas Avatar answered Oct 26 '22 17:10

David Thomas


jQuery closest() will travel up the tree and return the first element that matches the selector:

$(this).closest("form");
like image 25
Dennis Avatar answered Oct 26 '22 18:10

Dennis