Skip to content

Text Input

Create a text input field

  • Lesson
  • 2 min read
  • 2 of 8 in this chapter

Input element

The <input> element is just what it sounds like - it accepts input. It doesn't have a closing tag.

It can be displayed in a few different ways (a text field, a checkbox, a multiple choice question, etc.), and the type attribute specifies this.

We also need a name attribute, which is submitted with the user's input as a kind of label. The user doesn't actually see this on the form. Without a name attribute, that part of the form will not submit any data.

For now, we're just going to add a text input to our form:

HTML
<form>
<h1>Survey</h1>
<p>Tell us about yourself!</p>

<input type="text" name="first-name">

</form>

Label element

If you run the code above, you'll see that the text field appears without any explanation - the name attribute isn't displayed.

We can fix that using the <label> element. Notice that unlike the input element, the label element has a closing tag.

HTML
<label for="fname"></label>
<input type="text" name="first-name" id="fname">

The two elements, label and input, need to be linked together to show they are related (it's also helpful for accessibility purposes, for example for screen-readers). The value of id on the input should match the value of for on the label.