Using the <text> Element

Elements of type text create basic single-line text fields. The Try It example in this section will help you make your first text element. Text elements also have many attributes that can be helpful such as list, maxLength, minLength, size, and a few more. The section also introduces client-side validation of text fields which will be covered in detail later.

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

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

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

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