2

I'm trying to select the <form> element from an <input> element with JQuery. I've tried this:

$(".inputClass").parent("form")

but it doesn't seem to work.

2
  • 3
    Try $(".inputClass").closest("form") because the form may not be the direct parent of the input element Commented Dec 14, 2013 at 12:00
  • @ArunPJohny - Thank you. It works. If you post it like an answer I'll mark it. Commented Dec 14, 2013 at 12:03

3 Answers 3

8

In HTML 4 you can grab the ancestor that is a form element (by using parents (plural)), but HTML 5 allows a form control to be associated with a form that it not its ancestor, so you can't rely on that.

Form controls have a form property that will give you their associated form element.

var form = $(".inputClass").prop("form");

You can turn it into a jQuery object if you like.

var $form = $( form );

Or in one line:

var $form = $( $(".inputClass").prop("form") );
Sign up to request clarification or add additional context in comments.

1 Comment

Never knew this existed. Awesome.
4

Try $(".inputClass").closest("form") because the form may not be the direct parent of the input element

3 Comments

It is possible for a form element to not be a descendant of the form at all, so this won't always work.
But this is enough for me.
@ManoloSalsas in at least 95%(?) case, it's true, this is enough
0

The easiest way is to use the "form" property available to every form field.

var input = document.getElementById("foo");

var form = input.form;

No jQuery needed. Just good old fashioned DOM.

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.