HTMLFormElement - Web APIs 编辑
The HTMLFormElement
interface represents a <form>
element in the DOM. It allows access to—and, in some cases, modification of—aspects of the form, as well as access to its component elements.
<div id="interfaceDiagram" style="display: inline-block; position: relative; width: 100%; padding-bottom: 20%; vertical-align: middle; overflow: hidden;"><svg style="display: inline-block; position: absolute; top: 0; left: 0;" viewbox="-50 0 600 120" preserveAspectRatio="xMinYMin meet"><a xlink:href="https://developer.mozilla.org/wiki/en-US/docs/Web/API/EventTarget" target="_top"><rect x="1" y="1" width="110" height="50" fill="#fff" stroke="#D4DDE4" stroke-width="2px" /><text x="56" y="30" font-size="12px" font-family="Consolas,Monaco,Andale Mono,monospace" fill="#4D4E53" text-anchor="middle" alignment-baseline="middle">EventTarget</text></a><polyline points="111,25 121,20 121,30 111,25" stroke="#D4DDE4" fill="none"/><line x1="121" y1="25" x2="151" y2="25" stroke="#D4DDE4"/><a xlink:href="https://developer.mozilla.org/wiki/en-US/docs/Web/API/Node" target="_top"><rect x="151" y="1" width="75" height="50" fill="#fff" stroke="#D4DDE4" stroke-width="2px" /><text x="188.5" y="30" font-size="12px" font-family="Consolas,Monaco,Andale Mono,monospace" fill="#4D4E53" text-anchor="middle" alignment-baseline="middle">Node</text></a><polyline points="226,25 236,20 236,30 226,25" stroke="#D4DDE4" fill="none"/><line x1="236" y1="25" x2="266" y2="25" stroke="#D4DDE4"/><a xlink:href="https://developer.mozilla.org/wiki/en-US/docs/Web/API/Element" target="_top"><rect x="266" y="1" width="75" height="50" fill="#fff" stroke="#D4DDE4" stroke-width="2px" /><text x="303.5" y="30" font-size="12px" font-family="Consolas,Monaco,Andale Mono,monospace" fill="#4D4E53" text-anchor="middle" alignment-baseline="middle">Element</text></a><polyline points="341,25 351,20 351,30 341,25" stroke="#D4DDE4" fill="none"/><line x1="351" y1="25" x2="381" y2="25" stroke="#D4DDE4"/><a xlink:href="https://developer.mozilla.org/wiki/en-US/docs/Web/API/HTMLElement" target="_top"><rect x="381" y="1" width="110" height="50" fill="#fff" stroke="#D4DDE4" stroke-width="2px" /><text x="436" y="30" font-size="12px" font-family="Consolas,Monaco,Andale Mono,monospace" fill="#4D4E53" text-anchor="middle" alignment-baseline="middle">HTMLElement</text></a><polyline points="491,25 501,20 501,30 491,25" stroke="#D4DDE4" fill="none"/><line x1="501" y1="25" x2="509" y2="25" stroke="#D4DDE4"/><line x1="509" y1="25" x2="509" y2="90" stroke="#D4DDE4"/><line x1="509" y1="90" x2="492" y2="90" stroke="#D4DDE4"/><a xlink:href="https://developer.mozilla.org/wiki/en-US/docs/Web/API/HTMLFormElement" target="_top"><rect x="341" y="65" width="150" height="50" fill="#F4F7F8" stroke="#D4DDE4" stroke-width="2px" /><text x="416" y="94" font-size="12px" font-family="Consolas,Monaco,Andale Mono,monospace" fill="#4D4E53" text-anchor="middle" alignment-baseline="middle">HTMLFormElement</text></a></svg></div>
a:hover text { fill: #0095DD; pointer-events: all;}
Properties
This interface also inherits properties from its parent, HTMLElement
.
HTMLFormElement.elements
Read only- A
HTMLFormControlsCollection
holding all form controls belonging to this form element. HTMLFormElement.length
Read only- A
long
reflecting the number of controls in the form. HTMLFormElement.name
- A
DOMString
reflecting the value of the form'sname
HTML attribute, containing the name of the form. HTMLFormElement.method
- A
DOMString
reflecting the value of the form'smethod
HTML attribute, indicating the HTTP method used to submit the form. Only specified values can be set. HTMLFormElement.target
- A
DOMString
reflecting the value of the form'starget
HTML attribute, indicating where to display the results received from submitting the form. HTMLFormElement.action
- A
DOMString
reflecting the value of the form'saction
HTML attribute, containing the URI of a program that processes the information submitted by the form. HTMLFormElement.encoding
orHTMLFormElement.enctype
- A
DOMString
reflecting the value of the form'senctype
HTML attribute, indicating the type of content that is used to transmit the form to the server. Only specified values can be set. The two properties are synonyms. HTMLFormElement.acceptCharset
- A
DOMString
reflecting the value of the form'saccept-charset
HTML attribute, representing the character encoding that the server accepts. HTMLFormElement.autocomplete
- A
DOMString
reflecting the value of the form'sautocomplete
HTML attribute, indicating whether the controls in this form can have their values automatically populated by the browser. HTMLFormElement.noValidate
- A
Boolean
reflecting the value of the form'snovalidate
HTML attribute, indicating whether the form should not be validated.
Named inputs are added to their owner form instance as properties, and can overwrite native properties if they share the same name (e.g. a form with an input named action
will have its action
property return that input instead of the form's action
HTML attribute).
Methods
This interface also inherits methods from its parent, HTMLElement
.
checkValidity()
- Returns
true
if the element's child controls are subject to constraint validation and satisfy those constraints; returnsfalse
if some controls do not satisfy their constraints. Fires an event namedinvalid
at any control that does not satisfy its constraints; such controls are considered invalid if the event is not canceled. It is up to the programmer to decide how to respond tofalse
. reportValidity()
- Returns
true
if the element's child controls satisfy their validation constraints. Whenfalse
is returned, cancelableinvalid
events are fired for each invalid child and validation problems are reported to the user. requestSubmit()
- Requests that the form be submitted using the specified submit button and its corresponding configuration.
reset()
- Resets the form to its initial state.
submit()
- Submits the form to the server.
Deprecated methods
HTMLFormElement.requestAutocomplete()
- Triggers a native browser interface to assist the user in completing the fields which have an autofill field name value that is not
off
oron
. The form will receive an event once the user has finished with the interface, the event will either beautocomplete
when the fields have been filled orautocompleteerror
when there was a problem.
Events
Listen to these events using addEventListener()
, or by assigning an event listener to the oneventname
property of this interface.
formdata
- The
formdata
event fires after the entry list representing the form's data is constructed.
Also available via theonformdata
property. reset
- The
reset
event fires when a form is reset.
Also available via theonreset
property. submit
- The
submit
event fires when a form is submitted.
Also available via theonsubmit
property.
Usage notes
Obtaining a form element object
To obtain an HTMLFormElement
object, you can use a CSS selector with querySelector()
, or you can get a list of all of the forms in the document using its forms
property.
Document.forms
returns an array of HTMLFormElement
objects listing each of the forms on the page. You can then use any of the following syntaxes to get an individual form:
document.forms[index]
- Returns the form at the specified
index
into the array of forms. document.forms[id]
- Returns the form whose ID is
id
. document.forms[name]
- Returns the form whose
name
attribute's value isname
.
Accessing the form's elements
You can access the list of the form's data-containing elements by examining the form's elements
property. This returns an HTMLFormControlsCollection
listing all of the form's user data entry elements, both those which are descendants of the <form>
and those which are made members of the form using their form
attributes.
You can also get the form's element by using its name
attribute as a key of the form
, but using elements
is a better approach—it contains only the form's elements, and it cannot be mixed with other attributes of the form
.
Issues with Naming Elements
Some names will interfere with JavaScript access to the form’s properties and elements.
For example:
<input name="id">
will take precedence over<form id="…">
. This means thatform.id
will not refer to the form’s id, but to the element whose name is "id
". This will be the case with any other form properties, such as<input name="action">
or<input name="post">
.<input name="elements">
will render the form’selements
collection inaccessible. The referenceform.elements
will now refer to the individual element.
To avoid such problems with element names:
- Always use the
elements
collection to avoid ambiguity between an element name and a form property. - Never use "
elements
" as an element name.
If you are not using JavaScript, this will not cause a problem.
Elements that are considered form controls
The elements included by HTMLFormElement.elements
and HTMLFormElement.length
are the following:
<button>
<fieldset>
<input>
(with the exception that any whosetype
is"image"
are omitted for historical reasons)<object>
<output>
<select>
<textarea>
No other elements are included in the list returned by elements
, which makes it an excellent way to get at the elements most important when processing forms.
Examples
Creating a new form element, modifying its attributes, then submitting it:
const f = document.createElement("form"); // Create a form
document.body.appendChild(f); // Add it to the document body
f.action = "/cgi-bin/some.cgi"; // Add action and method attributes
f.method = "POST";
f.submit(); // Call the form's submit() method
Extract information from a <form>
element and set some of its attributes:
<form name="formA" action="/cgi-bin/test" method="post">
<p>Press "Info" for form details, or "Set" to change those details.</p>
<p>
<button type="button" onclick="getFormInfo();">Info</button>
<button type="button" onclick="setFormInfo(this.form);">Set</button>
<button type="reset">Reset</button>
</p>
<textarea id="form-info" rows="15" cols="20"></textarea>
</form>
<script>
function getFormInfo(){
// Get a reference to the form via its name
var f = document.forms["formA"];
// The form properties we're interested in
var properties = [ 'elements', 'length', 'name', 'charset', 'action', 'acceptCharset', 'action', 'enctype', 'method', 'target' ];
// Iterate over the properties, turning them into a string that we can display to the user
var info = properties.map(function(property) { return property + ": " + f[property] }).join("\n");
// Set the form's <textarea> to display the form's properties
document.forms["formA"].elements['form-info'].value = info; // document.forms["formA"]['form-info'].value would also work
}
function setFormInfo(f){ // Argument should be a form element reference.
f.action = "a-different-url.cgi";
f.name = "a-different-name";
}
</script>
Submit a <form>
into a new window:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Example new-window form submission</title>
</head>
<body>
<form action="test.php" target="_blank">
<p><label>First name: <input type="text" name="firstname"></label></p>
<p><label>Last name: <input type="text" name="lastname"></label></p>
<p><label><input type="password" name="pwd"></label></p>
<fieldset>
<legend>Pet preference</legend>
<p><label><input type="radio" name="pet" value="cat"> Cat</label></p>
<p><label><input type="radio" name="pet" value="dog"> Dog</label></p>
</fieldset>
<fieldset>
<legend>Owned vehicles</legend>
<p><label><input type="checkbox" name="vehicle" value="Bike">I have a bike</label></p>
<p><label><input type="checkbox" name="vehicle" value="Car">I have a car</label></p>
</fieldset>
<p><button>Submit</button></p>
</form>
</body>
</html>
Submitting forms and uploading files using XMLHttpRequest
If you want to know how to serialize and submit a form using the XMLHttpRequest
API, please read this paragraph.
Specifications
Specification | Status | Comment |
---|---|---|
HTML Living Standard The definition of 'HTMLFormElement' in that specification. | Living Standard | The following method has been added: requestAutocomplete() . |
HTML5 The definition of 'HTMLFormElement' in that specification. | Recommendation | The elements properties returns an HTMLFormControlsCollection instead of a raw HTMLCollection . This is mainly a technical change. The following method has been added: checkValidity() . The following properties have been added: autocomplete , noValidate , and encoding . |
Browser compatibility
BCD tables only load in the browser
See also
- The HTML element implementing this interface:
<form>
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论