3

I have multiple forms on a single page with the same named variables within each form.

I need to be able to changed the specific values for one form but not the others.

Ie.

I want to be able to set the value of Var2 for form2, but not the values of Var2 for form1.

Any ideas?

Thanks

1 Answer 1

3

Ideally, give the forms their own IDs and use the Descendant Selector:

$("#form1 input[name=foo]").val("something");

or select it by the order in which it appears in the DOM using eq (as Alxandr points out):

$("form:eq(0) input[name=foo]").val("something"); // select the first form
Sign up to request clarification or add additional context in comments.

2 Comments

Just to mention, this is given that the form1 has the id of form1. You can also change #form1 with form:eq(0) for instance. This will get the first form on the page, however, going with ids is the best way to go about it, because then you can replace the forms later etc.
Selecting the forms by their index/order in the page can be rather fragile, though. For instance, if you add/remove any other forms before the ones you are identifying. (say, a search box that is added to the whole site via the header/side bar)

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.