In jquery, how can I link to the current form using the click button

I have the form below; I changed the submit button to just type “Button” so that I can 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 several of these forms on one page, so I need to relatively refer to the form and some other inputs inside this form. What is the best way to do this? I thought about putting some kind of prefix that would be unique for each form, and then use this in a selector, but that seems very hacked ...

+4
source share
4 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"]'); }); }); 
+10
source

jQuery closest () will move through the tree and return the first element that matches the selector:

 $(this).closest("form"); 
+4
source
  $(this).siblings("input[name='name']"); // the field $(this).closest("form"); // the form 
+3
source
  $('.addToCartButton').click(function () { //need to reference current form here var the_form = $(this).closest("form"); //need to reference the hidden input with name="Name" above var the_input = the_form.find('input[name="name"]'); }); 
+1
source

All Articles