- HTML: HyperText Markup Language | MDN"> - HTML: HyperText Markup Language | MDN"> - HTML: HyperText Markup Language | MDN

  1. References
  2. HTML
  3. Elements
  4. <input>
  5. <input type="text">
Article Actions
  • English (US)
    • Remember language
    • Deutsch
    • Español
    • Français
    • 日本語
    • 中文 (简体)
  • Try it
  • Value
  • Additional attributes
  • Using text inputs
  • Validation
  • Examples
  • Technical summary
  • Specifications
  • Browser compatibility
  • See also
  1. HTML
  2. Tutorials
  3. HTML basics
  4. Introduction to HTML
    1. Introduction to HTML overview
    2. Getting started with HTML
    3. What's in the head? Metadata in HTML
    4. HTML text fundamentals
    5. Creating hyperlinks
    6. Advanced text formatting
    7. Document and website structure
    8. Debugging HTML
    9. Assessment: Marking up a letter
    10. Assessment: Structuring a page of content
  5. Multimedia and embedding
    1. Multimedia and embedding overview
    2. Images in HTML
    3. Video and audio content
    4. From object to iframe — other embedding technologies
    5. Adding vector graphics to the web
    6. Responsive images
    7. Assessment: Mozilla splash page
  6. HTML tables
    1. HTML tables overview
    2. HTML table basics
    3. HTML table advanced features and accessibility
    4. Assessment: Structuring planet data
  7. References
  8. HTML elements
    1. <a>
    2. <abbr>
    3. <acronym> Deprecated
    4. <address>
    5. <area>
    6. <article>
    7. <aside>
    8. <audio>
    9. <b>
    10. <base>
    11. <bdi>
    12. <bdo>
    13. <big> Deprecated
    14. <blockquote>
    15. <body>
    16. <br>
    17. <button>
    18. <canvas>
    19. <caption>
    20. <center> Deprecated
    21. <cite>
    22. <code>
    23. <col>
    24. <colgroup>
    25. <data>
    26. <datalist>
    27. <dd>
    28. <del>
    29. <details>
    30. <dfn>
    31. <dialog>
    32. <dir> Deprecated
    33. <div>
    34. <dl>
    35. <dt>
    36. <em>
    37. <embed>
    38. <fencedframe> Experimental
    39. <fieldset>
    40. <figcaption>
    41. <figure>
    42. <font> Deprecated
    43. <footer>
    44. <form>
    45. <frame> Deprecated
    46. <frameset> Deprecated
    47. <h1>
    48. <head>
    49. <header>
    50. <hgroup>
    51. <hr>
    52. <html>
    53. <i>
    54. <iframe>
    55. <img>
    56. <input>
    57. <ins>
    58. <kbd>
    59. <label>
    60. <legend>
    61. <li>
    62. <link>
    63. <main>
    64. <map>
    65. <mark>
    66. <marquee> Deprecated
    67. <menu>
    68. <meta>
    69. <meter>
    70. <nav>
    71. <nobr> Deprecated
    72. <noembed> Deprecated
    73. <noframes> Deprecated
    74. <noscript>
    75. <object>
    76. <ol>
    77. <optgroup>
    78. <option>
    79. <output>
    80. <p>
    81. <param> Deprecated
    82. <picture>
    83. <plaintext> Deprecated
    84. <portal> Experimental
    85. <pre>
    86. <progress>
    87. <q>
    88. <rb> Deprecated
    89. <rp>
    90. <rt>
    91. <rtc> Deprecated
    92. <ruby>
    93. <s>
    94. <samp>
    95. <script>
    96. <search>
    97. <section>
    98. <select>
    99. <slot>
    100. <small>
    101. <source>
    102. <span>
    103. <strike> Deprecated
    104. <strong>
    105. <style>
    106. <sub>
    107. <summary>
    108. <sup>
    109. <table>
    110. <tbody>
    111. <td>
    112. <template>
    113. <textarea>
    114. <tfoot>
    115. <th>
    116. <thead>
    117. <time>
    118. <title>
    119. <tr>
    120. <track>
    121. <tt> Deprecated
    122. <u>
    123. <ul>
    124. <var>
    125. <video>
    126. <wbr>
    127. <xmp> Deprecated
  9. Global attributes
    1. accesskey
    2. anchor Experimental Non-standard
    3. autocapitalize
    4. autocorrect Experimental
    5. autofocus
    6. class
    7. contenteditable
    8. data-*
    9. dir
    10. draggable
    11. enterkeyhint
    12. exportparts
    13. hidden
    14. id
    15. inert
    16. inputmode
    17. is
    18. itemid
    19. itemprop
    20. itemref
    21. itemscope
    22. itemtype
    23. lang
    24. nonce
    25. part
    26. popover
    27. slot
    28. spellcheck
    29. style
    30. tabindex
    31. title
    32. translate
    33. virtualkeyboardpolicy Experimental
    34. writingsuggestions
  10. Attributes
    1. accept
    2. autocomplete
    3. capture
    4. crossorigin
    5. dirname
    6. disabled
    7. elementtiming
    8. for
    9. max
    10. maxlength
    11. min
    12. minlength
    13. multiple
    14. pattern
    15. placeholder
    16. readonly
    17. rel
    18. required
    19. size
    20. step
  11. <input> types
    1. <input type="button">
    2. <input type="checkbox">
    3. <input type="color">
    4. <input type="date">
    5. <input type="datetime-local">
    6. <input type="email">
    7. <input type="file">
    8. <input type="hidden">
    9. <input type="image">
    10. <input type="month">
    11. <input type="number">
    12. <input type="password">
    13. <input type="radio">
    14. <input type="range">
    15. <input type="reset">
    16. <input type="search">
    17. <input type="submit">
    18. <input type="tel">
    19. <input type="text">
    20. <input type="time">
    21. <input type="url">
    22. <input type="week">
  12. Guides
    1. Content categories
    2. Block-level elements
    3. Inline elements
    4. Quirks Mode and Standards Mode
    5. Date and time formats used in HTML
    6. Constraint validation
    7. Microdata
    8. Microformats
    9. Viewport meta tag
    10. Allowing cross-origin use of images and canvas
  • Try it
  • Value
  • Additional attributes
  • Using text inputs
  • Validation
  • Examples
  • Technical summary
  • Specifications
  • Browser compatibility
  • See also

<input> elements of type text create basic single-line text fields.

Try it

Value

The value attribute is a string that contains the current value of the text entered into the text field. You can retrieve this using the HTMLInputElement value property in JavaScript.

jslet theText = myTextInput.value;

If no validation constraints are in place for the input (see Validation for more details), the value may be an empty string ("").

Additional attributes

In addition to the global attributes and the attributes that operate on all <input> elements regardless of their type, text inputs support the following attributes.

list

The values of the list attribute is the id of a <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 string length (measured in UTF-16 code units) that the user can enter into the text input. This must be an integer value of 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 string length (measured in UTF-16 code units) that the user can enter into the text input. This must be a 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

The pattern attribute, when specified, is a regular expression that the input's value must match 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; the '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.

Note: Use the 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.

See Specifying a pattern for further details and an example.

placeholder

The 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 must not 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 How to use Unicode controls for bidi text for more information.

Note: 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 <input> accessibility concerns for more information.

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 property.

Note: Because a read-only field cannot have a value, required does not have any effect on inputs with the readonly attribute also specified.

size

The 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 attribute.

spellcheck

The spellcheck global attribute is used to indicate whether 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 are:

false

Disable spell-checking for this element.

true

Enable spell-checking for this element.

"" (empty string) or no value

Follow the element's default behavior for spell-checking. This may be based upon a parent's 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.

Using text inputs

<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, or search term, you've got better options available).

Basic example

html<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 name=Chris (if "Chris" was entered as the input value before submission). You must remember to include name attribute on the <input> element, otherwise the text field's value won't be included with the submitted data.

Setting placeholders

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:

html<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 attribute).

Physical input element size

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:

html<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>

Validation

<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.

Note: 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 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.

A note on styling

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.

cssdiv { 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.

Making input required

You can use the required attribute as an easy way of making entering a value required before form submission is allowed:

html<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.

Input value length

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.

html<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.

Note: 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.

Specifying a pattern

You can use the 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 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.

html<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:

Examples

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.

Technical summary

Value A string representing the text contained in the text field.
Events change and input
Supported Common Attributes autocomplete, list, maxlength, minlength, pattern, placeholder, readonly, required and size
IDL attributes list, value
DOM interface

HTMLInputElement

Methods select(), setRangeText() and setSelectionRange().
Implicit ARIA Role with no list attribute: textbox with list attribute: combobox

Specifications

Specification
HTML Standard # text-(type=text)-state-and-search-state-(type=search)

Browser compatibility

BCD tables only load in the browser

See also

  • HTML Forms
  • <input> and the HTMLInputElement interface it's based upon.
  • <input type="search">
  • <textarea>: Multi-line text input
  • Compatibility of CSS properties

Help improve MDN

Was this page helpful to you?YesNoLearn how to contribute.

This page was last modified on Nov 21, 2024 by MDN contributors.

View this page on GitHub • Report a problem with this content

Từ khóa » Html Textbox Tag