5

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

4 Answers 4

15

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"]');
    });
});
Sign up to request clarification or add additional context in comments.

Comments

5

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

$(this).closest("form");

2 Comments

htanks for the quick response. what about referencing the other hidden fields inside the form, (now that you have the reference)
As others have pointed out, you can use find('input[name="name"]') although you might want to go with a more descriptive value than name, possibly formName?
3
 $(this).siblings("input[name='name']"); // the field
 $(this).closest("form");  // the form

Comments

1
 $('.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"]');
  });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.