<input>
elements of type
text
create basic single-line text fields.
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
| 值 |
A
DOMString
representing the text contained in the text field.
|
| 事件 |
change
and
input
|
| Supported Common Attributes |
autocomplete
,
list
,
maxlength
,
minlength
,
pattern
,
placeholder
,
readonly
,
required
and
size
|
| IDL attributes |
list
,
value
|
| 方法 |
select()
,
setRangeText()
and
setSelectionRange()
.
|
value
attribute is a
DOMString
that contains the current value of the text entered into the text field. You can retrieve this using the
value
property in JavaScript.
let theText = myTextInput.value;
If no validation constraints are in place for the input (see 验证 for more details), the value may be an empty string ("").
In addition to the attributes that operate on all
<input>
elements regardless of their type, text inputs support the following attributes:
| 属性 | 描述 |
|---|---|
list
|
The id of the <datalist> element that contains the optional pre-defined autocomplete options |
maxlength
|
The maximum number of characters the input should accept |
minlength
|
The minimum number of characters long the input can be and still be considered valid |
pattern
|
A regular expression the input's contents must match in order to be valid |
placeholder
|
An exemplar value to display in the input field whenever it is empty |
readonly
|
A Boolean attribute indicating whether or not the contents of the input should be read-only |
size
|
A number indicating how many characters wide the input field should be |
spellcheck
|
Controls whether or not to enable spell checking for the input field, or if the default spell checking configuration should be used |
list
The values of the list attribute is the
id
的
<datalist>
element located in the same document. The
<datalist>
provides a list of predefined values to suggest to the user for this input. Any values in the list that are not compatible with the
type
are not included in the suggested options. The values provided are suggestions, not requirements: users can select from this predefined list or provide a different value.
maxlength
The maximum number of characters (as UTF-16 code units) the user can enter into the
text
input. This must be an integer value 0 or higher. If no
maxlength
is specified, or an invalid value is specified, the
text
input has no maximum length. This value must also be greater than or equal to the value of
minlength
.
The input will fail
constraint validation
if the length of the text value of the field is greater than
maxlength
UTF-16 code units long. Constraint validation is only applied when the value is changed by the user.
minlength
The minimum number of characters (as UTF-16 code units) the user can enter into the
text
input. This must be an non-negative integer value smaller than or equal to the value specified by
maxlength
. If no
minlength
is specified, or an invalid value is specified, the
text
input has no minimum length.
The input will fail
constraint validation
if the length of the text entered into the field is fewer than
minlength
UTF-16 code units long. Constraint validation is only applied when the value is changed by the user.
pattern
pattern
attribute, when specified, is a regular expression that the input's
value
must match in order for the value to pass
constraint validation
. It must be a valid JavaScript regular expression, as used by the
RegExp
type, and as documented in our
guide on regular expressions
;
'u'
flag is specified when compiling the regular expression, so that the pattern is treated as a sequence of Unicode code points, instead of as ASCII. No forward slashes should be specified around the pattern text.
If the specified pattern is not specified or is invalid, no regular expression is applied and this attribute is ignored completely.
提示:
使用
title
attribute to specify text that most browsers will display as a tooltip to explain what the requirements are to match the pattern. You should also include other explanatory text nearby.
见 Specifying a pattern for further details and an example.
placeholder
placeholder
attribute is a string that provides a brief hint to the user as to what kind of information is expected in the field. It should be a word or short phrase that demonstrates the expected type of data, rather than an explanatory message. The text
不必
include carriage returns or line feeds.
If the control's content has one directionality ( LTR or RTL ) but needs to present the placeholder in the opposite directionality, you can use Unicode bidirectional algorithm formatting characters to override directionality within the placeholder; see Overriding BiDi using Unicode control characters in The Unicode Bidirectional Text Algorithm for those characters.
注意:
Avoid using the
placeholder
attribute if you can. It is not as semantically useful as other ways to explain your form, and can cause unexpected technical issues with your content. See
Labels and placeholders
in
<input>: The Input (Form Input) element
了解更多信息。
readonly
A Boolean attribute which, if present, means this field cannot be edited by the user. Its
value
can, however, still be changed by JavaScript code directly setting the
HTMLInputElement.value
特性。
注意:
Because a read-only field cannot have a value,
required
does not have any effect on inputs with the
readonly
attribute also specified.
size
size
attribute is a numeric value indicating how many characters wide the input field should be. The value must be a number greater than zero, and the default value is 20. Since character widths vary, this may or may not be exact and should not be relied upon to be so; the resulting input may be narrower or wider than the specified number of characters, depending on the characters and the font (
font
settings in use).
This does
not
set a limit on how many characters the user can enter into the field. It only specifies approximately how many can be seen at a time. To set an upper limit on the length of the input data, use the
maxlength
属性。
spellcheck
spellcheck
is a global attribute which is used to indicate whether or not to enable spell checking for an element. It can be used on any editable content, but here we consider specifics related to the use of
spellcheck
on
<input>
elements. The permitted values for
spellcheck
是:
false
Disable spell checking for this element.
true
Enable spell checking for this element.
spellcheck
setting or other factors.
An input field can have spell checking enabled if it doesn't have the readonly attribute set and is not disabled.
The value returned by reading
spellcheck
may not reflect the actual state of spell checking within a control, if the
user agent's
preferences override the setting.
The following non-standard attributes are also available on some browsers. As a general rule, you should avoid using them unless it can't be helped.
| 属性 | 描述 |
|---|---|
autocorrect
|
A string indicating whether or not autocorrect is
on
or
off
.
Safari only.
|
mozactionhint
|
A string indicating the type of action that will be taken when the user presses the Enter or 返回 key while editing the field; this is used to determine an appropriate label for that key on a virtual keyboard. Firefox for Android only. |
autocorrect
A Safari extension, the
autocorrect
attribute is a string which indicates whether or not to activate automatic correction while the user is editing this field. Permitted values are:
on
Enable automatic correction of typos, as well as processing of text substitutions if any are configured.
off
Disable automatic correction and text substitutions.
mozactionhint
A Mozilla extension, supported by Firefox for Android, which provides a hint as to what sort of action will be taken if the user presses the Enter or 返回 key while editing the field. This information is used to decide what kind of label to use on the Enter key on the virtual keyboard.
注意:
This
has been standardized
as the global attribute
enterkeyhint
, but is not yet widely implemented. To see the status of the change being implemented in Firefox, see
bug 1490661
.
Permitted values are:
go
,
done
,
next
,
search
,和
send
. The browser decides, using this hint, what label to put on the enter key.
<input>
elements of type
text
create basic, single-line inputs. You should use them anywhere you want the user to enter a single-line value and there isn't a more specific input type available for collecting that value (for example, if it's a
date
,
URL
,
email
,或
search term
, you've got better options available).
<form>
<div>
<label for="uname">Choose a username: </label>
<input type="text" id="uname" name="name">
</div>
<div>
<button>Submit</button>
</div>
</form>
This renders like so:
When submitted, the data name/value pair sent to the server will be
uname=Chris
(if "Chris" was entered as the input value before submission). You must remember to include
name
属性在
<input>
element, otherwise the text field's value won't be included with the submitted data.
You can provide a useful placeholder inside your text input that can provide a hint as to what to enter by including using the
placeholder
attribute. Look at the following example:
<form>
<div>
<label for="uname">Choose a username: </label>
<input type="text" id="uname" name="name"
placeholder="Lower case, all one word">
</div>
<div>
<button>Submit</button>
</div>
</form>
You can see how the placeholder is rendered below:
The placeholder is typically rendered in a lighter color than the element's foreground color, and automatically vanishes when the user begins to enter text into the field (or whenever the field has a value set programmatically by setting its
value
属性。
The physical size of the input box can be controlled using the
size
attribute. With it, you can specify the number of characters the text input can display at a time. This affects the width of the element, letting you specify the width in terms of characters rather than pixels. In this example, for instance, the input is 30 characters wide:
<form>
<div>
<label for="uname">Choose a username: </label>
<input type="text" id="uname" name="name"
placeholder="Lower case, all one word"
size="30">
</div>
<div>
<button>Submit</button>
</div>
</form>
<input>
elements of type
text
have no automatic validation applied to them (since a basic text input needs to be capable of accepting any arbitrary string), but there are some client-side validation options available, which we'll discuss below.
注意 : HTML form validation is not a substitute for server-scripts that ensure the entered data is in the proper format. It's far too easy for someone to make adjustments to the HTML that allow them to bypass the validation, or to remove it entirely. It's also possible for someone to simply bypass your HTML entirely and submit the data directly to your server. If your server-side code fails to validate the data it receives, disaster could strike when improperly-formatted data (or data which is too large, is of the wrong type, and so forth) is entered into your database.
There are useful pseudo-classes available for styling form elements to help the user see when their values are valid or invalid. These are
:valid
and
:invalid
. In this section, we'll use the following CSS, which will place a check (tick) mark next to inputs containing valid values, and a cross (X) next to inputs containing invalid values.
div {
margin-bottom: 10px;
position: relative;
}
input + span {
padding-right: 30px;
}
input:invalid+span:after {
position: absolute; content: '✖';
padding-left: 5px;
}
input:valid+span:after {
position: absolute;
content: '✓';
padding-left: 5px;
}
The technique also requires a
<span>
element to be placed after the form element, which acts as a holder for the icons. This was necessary because some input types on some browsers don't display icons placed directly after them very well.
可以使用
required
attribute as an easy way of making entering a value required before form submission is allowed:
<form>
<div>
<label for="uname">Choose a username: </label>
<input type="text" id="uname" name="name" required>
<span class="validity"></span>
</div>
<div>
<button>Submit</button>
</div>
</form>
div { margin-bottom: 10px; position: relative; } input + span { padding-right: 30px; } input:invalid+span:after { position: absolute; content: '✖'; padding-left: 5px; } input:valid+span:after { position: absolute; content: '✓'; padding-left: 5px; }
This renders like so:
If you try to submit the form with no search term entered into it, the browser will show an error message.
You can specify a minimum length (in characters) for the entered value using the
minlength
attribute; similarly, use
maxlength
to set the maximum length of the entered value, in characters.
The example below requires that the entered value be 4–8 characters in length.
<form>
<div>
<label for="uname">Choose a username: </label>
<input type="text" id="uname" name="name" required size="10"
placeholder="Username"
minlength="4" maxlength="8">
<span class="validity"></span>
</div>
<div>
<button>Submit</button>
</div>
</form>
div { margin-bottom: 10px; position: relative; } input + span { padding-right: 30px; } input:invalid+span:after { position: absolute; content: '✖'; padding-left: 5px; } input:valid+span:after { position: absolute; content: '✓'; padding-left: 5px; }
This renders like so:
If you try to submit the form with less than 4 characters, you'll be given an appropriate error message (which differs between browsers). If you try to enter more than 8 characters, the browser won't let you.
注意:
If you specify a
minlength
but do not specify
required
, the input is considered valid, since the user is not required to specify a value.
可以使用
pattern
attribute to specify a regular expression that the inputted value must match in order to be considered valid (see
Validating against a regular expression
for a simple crash course on using regular expressions to validate inputs).
The example below restricts the value to 4-8 characters and requires that it contain only lower-case letters.
<form>
<div>
<label for="uname">Choose a username: </label>
<input type="text" id="uname" name="name" required size="45"
pattern="[a-z]{4,8}">
<span class="validity"></span>
<p>Usernames must be lowercase and 4-8 characters in length.</p>
</div>
<div>
<button>Submit</button>
</div>
</form>
div {
margin-bottom: 10px;
position: relative;
}
p {
font-size: 80%;
color: #999;
}
input + span {
padding-right: 30px;
}
input:invalid+span:after {
position: absolute;
content: '✖';
padding-left: 5px;
}
input:valid+span:after {
position: absolute;
content: '✓';
padding-left: 5px;
}
This renders like so:
You can see good examples of text inputs used in context in our Your first HTML form and How to structure an HTML form articles.
| 规范 | 状态 | 注释 |
|---|---|---|
|
HTML 实时标准
The definition of '<input type="text">' in that specification. |
实时标准 | 初始定义 |
|
HTML 5.1
The definition of '<input type="text">' in that specification. |
推荐 | 初始定义 |
| 桌面 | 移动 | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
type="text"
|
Chrome 完整支持 1 | Edge 完整支持 12 | Firefox 完整支持 1 | IE 完整支持 Yes | Opera 完整支持 Yes | Safari 完整支持 1 | WebView Android 完整支持 Yes | Chrome Android 完整支持 Yes | Firefox Android 完整支持 4 | Opera Android 完整支持 Yes | Safari iOS 完整支持 Yes | Samsung Internet Android 完整支持 Yes |
完整支持
<input>
和
HTMLInputElement
interface it's based upon.
<input type="search">
<textarea>
: Multi-line text input
<button>
<datalist>
<fieldset>
<form>
<input>
<label>
<legend>
<meter>
<optgroup>
<option>
<output>
<progress>
<select>
<textarea>
<input>
类型
<input type="button">
<input type="checkbox">
<input type="color">
<input type="date">
<input type="datetime">
<input type="datetime-local">
<input type="email">
<input type="file">
<input type="hidden">
<input type="image">
<input type="month">
<input type="number">
<input type="password">
<input type="radio">
<input type="range">
<input type="reset">
<input type="search">
<input type="submit">
<input type="tel">
<input type="text">
<input type="time">
<input type="url">
<input type="week">