最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin4浏览0评论

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 .asp?filename=tryhtml5_input_form

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

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']")

Share Improve this question edited Dec 16, 2011 at 14:18 Paralife asked Dec 16, 2011 at 13:47 ParalifeParalife 6,2368 gold badges42 silver badges65 bronze badges 3
  • api.jquery.com/input-selector – Zoltan Toth Commented Dec 16, 2011 at 13:49
  • Do you want only <input> elements, or all the types which are selected by ':input' (<input>, <textarea>, <select>, and <button>)? – Šime Vidas Commented Dec 16, 2011 at 14:53
  • @Vidas all of them: Whatever would be used by the browser to gather the parameters to send to the server on a submit of the form. – Paralife Commented Dec 17, 2011 at 12:47
Add a comment  | 

4 Answers 4

Reset to default 12

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/

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

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

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.

Try

var $my_input_fields = $(":input");
发布评论

评论列表(0)

  1. 暂无评论