Paralife
Paralife

Reputation: 6236

Is there any way to select all input elements of a form including those outside it?

Is there an 'official' way to get all input elements of a form including those outside of the form that use the new HTML5 'form' attribute for input elements, or do I have to make a union of some custom selectors? By official i mean standard idiom or jQuery provided. Thanks.

EDIT: See this example http://www.w3schools.com/html5/tryit.asp?filename=tryhtml5_input_form

EDIT2: I ended up doing this: $("#formId :input, :input[form='formId']")

Upvotes: 7

Views: 9018

Answers (4)

Šime Vidas
Šime Vidas

Reputation: 185893

Yes, there is a way.

The form.elements collection holds all form controls - both those who are within the form, and those who are associated with it via the form attribute.

So, just get the reference to the form, and retrieve the .elements property:

var form = document.getElementById( 'form1' );
var allFormControls = form.elements;

Live demo: http://jsfiddle.net/bsFcf/

If you want to place all form controls inside a jQuery object, I recommend this:

$( $( '#form1' )[0].elements )

Live demo: http://jsfiddle.net/bsFcf/1/

Upvotes: 12

Brad Christie
Brad Christie

Reputation: 101604

In case you were referring to the new form="myform" attribute you can now add to elements, and want to select elements based on that, you can do the following:

$('[form="myform"]');

Using the attribute selector.

Upvotes: 2

Thariama
Thariama

Reputation: 50832

Try

var $my_input_fields = $(":input");

Upvotes: 1

Frédéric Hamidi
Frédéric Hamidi

Reputation: 262919

You can combine a descendant selector and a has attribute selector:

var $inputs = $("form :input, :input[form]");

Upvotes: 4

Related Questions