Categories
HTML Tutorials

Using the input element for text input

If you set the type attribute to text, the browser will display a single-line text box. This is the same style for the input element that you saw in the last chapter, and the style that is used when you omit the type attribute entirely. Below are the attributes that are available for this input element type.

Specifying the Element Size

There are two attributes that have an effect on the size of the text box. The maxlength attribute specifies an upper limit for the number of characters that the user can enter, and the size attribute specifies how many characters the text box can display. For both attributes, the number of characters is expressed as a positive integer value.

Using the maxlength and size Attributes
<html>
  <head>
    <title>Example</title>
    <meta name="author" content="Adam Freeman"/>
    <meta name="description" content="A simple example"/>
    <link rel="shortcut icon" href="favicon.ico" type="image/x-icon" />
  </head>
  <body>
    <form method="post" action="http://titan:8080/form">
      <p>
        <label for="name">
          Name: <input maxlength="10" id="name" name="name"/>
        </label>
      </p>
      <p>
        <label for="city">
          City: <input size="10" id="city" name="city"/>
        </label>
      </p>
      <p>
        <label for="fave">
          Fruit: <input size="10" maxlength="10" id="fave" name="fave"/>
        </label>
      </p>
      <button type="submit">Submit Vote</button>
    </form>
  </body>
</html>

For the first input element, we have applied the maxlength attribute with a value of 10. This means that the browser is free to determine the amount of space that the text box occupies on the screen, but the user can only enter up to ten characters. If the user tries to enter more than ten characters, the browser will discard the input.

For the second input element, we have applied the size attribute, also with a value of 10. This means that the browser must ensure that it sizes the text box so that it can display ten characters. The size attribute doesn’t apply any restriction on the number of characters that the user can enter.

We have applied both attributes to the third input element. This has the effect of fixing the size onscreen and limiting the number of characters that the user can enter. You can see how these attributes affect the display and data entry below.