Chapter 22: Text Input Types & Attributes

type="text" – Single Line Text Input

The universal text conduit: Fallback mechanics, single-line text buffers, mobile keyboard configurations, and accessible name computation.

LEARNING OBJECTIVES
  • Understand the internal line-stripping and text normalization mechanics of single-line text fields.
  • Configure virtual mobile keyboards using the inputmode and enterkeyhint attributes without altering form submission data types.
  • Control client-side text ergonomics using autocapitalize, autocorrect, and spellcheck.
  • Master the W3C Accessible Name Computation (AccName 1.2) algorithm for single-line text inputs.
🎬 INTERACTIVE VISUAL PIPELINE Core Architecture Simulation
🌐
1. Input
Directives & Tags
⚙️
2. Parse
Tokenizer & AST
🌳
3. Layout
Box Model & Flow
🎨
4. Render
GPU Paint & Composite
PHASE 1: INPUT & DIRECTIVES
Browser receives declarative markup stream, parsing tag tokens and initializing component state.

📖 The Mental Model & Story (Intuitive Foundation)

Imagine filling out a physical passport application form. You are given a small, single-height rectangular white box labeled "First Name".

+-------------------------------------------------------------+
| First Name: [ J A N E                                     ] |
+-------------------------------------------------------------+

Because the box is only one line tall, you cannot press "Return" and start writing a second paragraph underneath. If you try to write two lines of text inside that box, the postal clerk will hand it back or strike it through. Furthermore, depending on the field (such as "PIN Code" vs "Street Address"), an assistant might hand you a specialized numeric stamp instead of a calligraphy pen.

In HTML, <input type="text"> is that exact single-line bounded box. It is the baseline workhorse of web forms. Regardless of whether you paste a ten-page essay with fifty paragraphs into a type="text" field, the browser's rendering engine automatically strips or collapses line breaks into a single continuous stream of characters.


Technical Deep Dive & Specifications

The Single-Line Buffer & Text Normalization

Under the WHATWG specification, the text state represents a single line of plain text. When text is inserted into an <input type="text"> (either via user typing, clipboard paste, or DOM scripting):

  1. Newline Stripping: Any Carriage Return (\r) or Line Feed (\n) characters are converted to spaces or stripped entirely, preventing multi-line entries.
  2. Text Directionality: Bidirectional text (combining Left-to-Right English with Right-to-Left Arabic/Hebrew) is rendered using the Unicode Bidirectional Algorithm (Bidi).
User pastes text:
"Line One\nLine Two\r\nLine Three"
                 |
                 v [HTML Input Normalization Engine]
Result in buffer:
"Line One Line Two Line Three"

Mobile Ergonomics: inputmode & enterkeyhint

A common junior mistake is changing type="text" to type="number" or type="tel" merely to bring up a specific mobile keyboard on smartphones. However, doing so triggers unwanted numeric stepper arrows, scientific notation parsing (1e5), or aggressive validation rules.

The modern standard separates data type semantics from keyboard presentation using the inputmode and enterkeyhint attributes:

+-------------------------------------------------------------------------------+
|                             VIRTUAL KEYBOARD ENGINE                           |
+-------------------------------------------------------------------------------+
        |                                                   |
        v                                                   v
  [inputmode="numeric"]                             [enterkeyhint="search"]
  Displays numeric keypad (0-9)                     Changes action button to
  without altering DOMString type                   "Search" magnifying glass

The inputmode Matrix

inputmode Value Mobile Keyboard Displayed Best Use Case
text (default) Standard alphanumeric keyboard General text, names, descriptions
numeric Digits 0–9 keypad Credit card numbers, OTP / 2FA codes, PINs
decimal Digits 0–9 plus decimal separator (. or ,) Monetary amounts, currency entries
tel Phone dial pad (0-9, *, #, +) Phone numbers (when not using type="tel")
search Alphanumeric with dedicated "Search" key Search bars and filter fields
email Alphanumeric with @ and .com shortcuts Email fields
url Alphanumeric with / and .com shortcuts Website addresses
none Suppresses virtual keyboard entirely Custom on-screen virtual keyboards / pinpads

The enterkeyhint Attribute

Controls the label/action of the Enter / Return key on virtual mobile keyboards:

  • enterkeyhint="go" (Label: "Go")
  • enterkeyhint="done" (Label: "Done" - closes keyboard)
  • enterkeyhint="next" (Label: "Next" - jumps focus to next field)
  • enterkeyhint="search" (Label: "Search" or magnifying glass icon)
  • enterkeyhint="send" (Label: "Send" or paper plane icon)

Text Assistance Attributes

<input 
  type="text"
  name="full_name"
  autocapitalize="words"
  autocorrect="off"
  spellcheck="false"
  autocomplete="name">
  • autocapitalize: Controls automatic capitalization on mobile devices:
    • none or off: No capitalization.
    • sentences or on: Capitalizes the first letter of each sentence (default).
    • words: Capitalizes the first letter of every word (ideal for First/Last names, cities).
    • characters: Capitalizes every character (ideal for Promo Codes, State abbreviations, License plates).
  • spellcheck: Boolean attribute (true or false) controlling native browser red squiggly spell-checking lines.
  • autocorrect: Non-standard but widely supported Safari/Chromium attribute (on or off) controlling aggressive autocorrect dictionaries.

Accessible Name Computation (AccName 1.2)

Screen readers (such as NVDA, JAWS, VoiceOver) cannot announce an input field intelligently unless it has an accessible name. The W3C Accessible Name and Description Computation specification computes the name according to this deterministic priority order:

                            Accessible Name Priority (AccName 1.2)
                                              |
                     1. Does 'aria-labelledby' exist?
                                    / \
                              Yes  /   \  No
                                  v     \
                [Read referenced element] \
                                           v
                              2. Does 'aria-label' exist?
                                          / \
                                    Yes  /   \  No
                                        v     \
                              [Read aria-label] \
                                                 v
                               3. Is there a linked <label for="id"> or parent <label>?
                                                / \
                                          Yes  /   \  No
                                              v     \
                                    [Read <label> text] \
                                                         v
                                           4. Does 'placeholder' exist?
                                                        / \
                                                  Yes  /   \  No
                                                      v     \
                                            [Read placeholder]v
                                                    5. Does 'title' exist?
                                                              |
                                                              v
                                                    [Read title / Unnamed]

[!IMPORTANT] The gold standard for production HTML is always an explicit <label for="input-id"> association. Never rely on placeholder or title as the primary accessible name.


SYS: ACTIVE
HULL: 98%
CORE: STABLE
NET: ONLINE
HTML STARSHIP CODE TERMINAL example.html
LIVE RENDER & DIAGNOSTICS CORE TEMP: 45°C
INSPECTING DOM: VALID
TAGS: SCANNING...

💻 Interactive Code Playground

Starter Code

Line-by-Line Code Breakdown

  • Line 26 (<label for="usr-name">Full Legal Name</label>): Programmatically attaches the label to the input via matching id="usr-name", guaranteeing top accessibility compliance under AccName 1.2.
  • Line 27–34 (<input type="text" ... autocapitalize="words" autocomplete="name">): Configures the mobile IME to capitalize words automatically and instructs the browser's password manager / autofill vault to supply the user's stored legal name.
  • Line 41–48 (<input ... autocapitalize="characters" enterkeyhint="done">): Optimizes promo code entry by triggering all-caps typing and presenting a "Done" button on virtual keyboards.
  • Line 57–70 (Selection Range Script): Demonstrates the DOM API (selectionStart, selectionEnd) which allows programmatic manipulation and inspection of the text cursor.

Expected Browser Render Output


SYS: ACTIVE
HULL: 98%
CORE: STABLE
NET: ONLINE
HTML STARSHIP CODE TERMINAL playground.html
LIVE RENDER & DIAGNOSTICS CORE TEMP: 45°C
INSPECTING DOM: VALID
TAGS: SCANNING...
Text Input Configuration Lab

Full Legal Name
[ e.g. Eleanor Vance                          ]
Mobile keyboard will automatically capitalize the first letter of each word.

Voucher / Promo Code
[ SUMMER2026                                  ]
Mobile keyboard will lock uppercase mode and display a "Done" action button.

Active Element: #promo-code
Live Value: "DISCOUNT50"
Selection Range: Start: 0 | End: 8 | Selected Text: "DISCOUNT"

🏋️ Hands-On Exercise

🎯 The Challenge: Build an Accessible Quick-Search & Command Bar

Instructions:

  1. Create a search form with action="/search" and method="GET".
  2. Add a single-line text input with id="global-search", name="query".
  3. Link an explicit <label for="global-search"> with the text "Search Knowledge Base".
  4. Configure the input with:
    • inputmode="search" to trigger a mobile search keyboard.
    • enterkeyhint="search" to show a search icon on mobile return keys.
    • autocapitalize="none" to prevent unwanted initial capitalization.
    • autocomplete="off" to prevent native browser history dropdowns from obscuring custom UI results.
  5. Add a button styled with "Search".

🏁 Starter Code Sandbox

SYS: ACTIVE
HULL: 98%
CORE: STABLE
NET: ONLINE
STARTER CODE SANDBOX exercise.html
LIVE RENDER & DIAGNOSTICS CORE TEMP: 45°C
INSPECTING DOM: VALID
TAGS: SCANNING...

⚠️ Common Pitfalls

  1. Using type="number" for Credit Cards or OTP Codes: type="number" strips leading zeroes (turning 0123 into 123), adds numeric increment spinners, and allows scientific notation (e). Use <input type="text" inputmode="numeric" pattern="[0-9]*"> instead.
  2. Forgetting for/id on Labels: Placing a <label>Name:</label> next to <input type="text"> without a matching for="id" creates an orphan label. Screen reader users will hear "Edit text, blank" without knowing what information is requested.
  3. Relying on JavaScript Keypress Interception for Capitalization: Don't use JavaScript oninput = (e) => e.target.value.toUpperCase() when autocapitalize="characters" achieves mobile IME lock natively and CSS text-transform: uppercase handles presentation cleanly.

💡 Pro Tips

  1. Programmatic Cursor Control with setRangeText(): Use input.setRangeText(replacement, start, end, 'select') to insert tokens, markdown tags, or emojis at the exact cursor position without breaking browser undo/redo history stacks.
  2. Combine autocomplete with type="text" for Instant Conversions: Always specify granular WHATWG autocomplete tokens (e.g., autocomplete="address-line1", autocomplete="one-time-code", autocomplete="cc-number"). This boosts form completion rates by over 30% on mobile browsers.

📌 Key Takeaways

  • <input type="text"> enforces a single-line plain text buffer; newlines are automatically normalized or stripped.
  • inputmode and enterkeyhint customize mobile virtual touch keyboards without changing form serialization types.
  • autocapitalize, autocorrect, and spellcheck provide fine-grained control over client-side text editing ergonomics.
  • Accessible Name Computation prioritizes aria-labelledby > aria-label > <label> > placeholder > title.
  • Standard <label for="id"> association remains the universal industry best practice for accessibility.
  • --
⭐ LEARN: HTML 🌟 ⚔️ QUIZ BATTLE ARENA // ACTIVE
3x
STREAK!
BONUS ACTIVE
COMBO
? Question 1 / 3

What is the best way to prompt a mobile device to open a numeric keypad for a 6-digit SMS verification code while preserving leading zeros?

Question 1 / 3 Topic: HTML Fundamentals
00:45 REMAINING
XP REWARD
+250 XP
3x
STREAK!
BONUS ACTIVE
COMBO
? Question 2 / 3

According to the W3C Accessible Name Computation algorithm (AccName 1.2), which of the following takes the HIGHEST precedence for an input's accessible name?

Question 2 / 3 Topic: HTML Fundamentals
00:45 REMAINING
XP REWARD
+250 XP
3x
STREAK!
BONUS ACTIVE
COMBO
? Question 3 / 3

What happens if a user pastes the string "Hello\nWorld" into an <input type="text">?

Question 3 / 3 Topic: HTML Fundamentals
00:45 REMAINING
XP REWARD
+250 XP