HTML

HTML input Tag: The Input Element

The HTML <input> tag is a form element to collect user input. The input element works with many different input types, including colors, files, and text.

How to Use the HTML input Tag

Every input element needs a type attribute to define the type of input to collect. Some common input types include:

  • text: Creates standard text input.
  • email: Accepts only valid email addresses.
  • number: Accepts only numerical values.
  • password: Masks any text input behind a password character.

The <input> tag also accepts optional attributes like name, value, and the placeholder attribute. As an empty tag, <input> only has an opening tag but no closing tag.

<form>
    <label for="username">Username:</label>
    <input type="text" id="username" name="username" placeholder="Enter your username">

    <label for="password">Password:</label>
    <input type="password" id="password" name="password" placeholder="Enter your password">

    <label for="email">Email:</label>
    <input type="email" id="email" name="email" placeholder="Enter your email">

    <label for="number">Age:</label>
    <input type="number" id="number" name="age" min="1" max="120" placeholder="Enter your age">

    <input type="submit" value="Submit">
</form>
  • type: Specifies the type of data the <input> element should handle.
  • name: The optional attribute to define the name of the input element for sending data.
  • value: An optional attribute to represent the default value for sending data.
  • placeholder: An optional attribute to provide a hint to the user about what to put into the input box.

When to Use the HTML input Tag

The <input> tag is essential for collecting and processing most types of input. From text-based registration details to color codes and file paths, using the <input> tag is the go-to solution.

Collecting Text-Based Data

You can use the input element to collect details like usernames, passwords, and email addresses. For passwords, you can set the type attribute to "password" to mask the input.

<form>
    <input type="text" name="username" placeholder="Username">
    <input type="password" name="password" placeholder="Password">
    <input type="email" name="email" placeholder="Email">
    <input type="submit" value="Register">
</form>

Gathering Numerical Data

Also you collect numerical data like ages, scores, and monetary values using the <input> tag. The number and range input types ensures that users can only input numerical values.

<form>
    <input type="number" name="quantity" placeholder="Quantity" min="1" max="100">
    <input type="range" name="score" min="0" max="10">
</form>

Uploading Files

By setting the type attribute to "file", you can also allow users to upload documents, images, or other files.

<form>
    <label>Upload your file:</label>
    <input type="file" name="fileupload">
    <input type="submit" value="Upload">
</form>

Searching and Filtering Content

Moreover, you can use the search input type to filter or find relevant content.

<form>
    <input type="search" name="site-search" placeholder="Search the site...">
    <input type="submit" value="Search">
</form>

Choosing Dates and Times

Date and time inputs help users select the correct dates and times, making scheduling and calendar functions easier.

<form>
    <input type="date" name="event-date">
    <input type="time" name="event-time">
</form>

Examples of Using Input in HTML

Countless websites use the input element to accept different types of input from users. Here are some simple examples:

Landing Page Newsletter Signup

Landing pages of websites often contain a newsletter signup form to collect email addresses. Such forms might use the <input> tag with type="email" to ensure that the email addresses are valid.

<form>
    <input type="email" name="email" placeholder="Enter your email">
    <input type="submit" value="Subscribe">
</form>

Job Application Form

A job application page might use an input element of type "file" to accept resumes from candidates.

<form>
    <label>Upload your resume:</label>
    <input type="file" name="resume">
    <input type="submit" value="Submit Application">
</form>

Checkout Pages

Many e-commerce websites use dedicated web pages for their checkout processes. For payment sections on checkout pages, input elements can collect credit card information, numbers, and dates.

<form>
    <input type="number" name="amount" placeholder="Amount">
    <input type="text" name="card_number" placeholder="Card Number">
    <input type="date" name="expiry">
    <input type="submit" value="Pay Now">
</form>

Product Search Bar

An e-commerce platform might also use the <input> tag to create a search bar that lets users search for and find specific products.

<form>
    <input type="search" name="site-search" placeholder="Search for products...">
    <input type="submit" value="Search">
</form>

Learn More About Input in HTML

Additional HTML Input Types

HTML input elements support a range of additional input types for different use cases. Here’s an overview of the input types in HTML:

  • text: Allows users to enter text for submission.
  • password: Masks the text entered for security purposes.
  • email: Ensures the user input is in a valid email address format.
  • number: Using the type number, the HTML input element accepts only numerical values. By additionally setting the min and max attributes, you can define lower and upper bounds.
  • range: Provides a slider interface for selecting a numeric value. Using an optional step attribute, you can define the interval between the values.
  • date: Allows users to pick a calendar date, ensuring a valid date value.
  • time: Allows users to select a specific time of the day, ensuring a valid time value.
  • datetime-local: Combines date and time input in HTML, accepting year, month, and day as well as the time in hours and minutes.
  • search: Accepts text in an optimized way for search fields.
  • url: Ensures the user input matches URL formatting.
  • tel: Allows users to enter phone numbers, with attributes like pattern defining the format.
  • color: Displays an operating system's color picker for selecting a color.
  • file: Enables file selection using a system dialog. Using an optional accept attribute, you can add unique file type specifiers like "image/*" to limit the file types.

<form>
    <input type="text" name="text">
    <input type="password" name="password">
    <input type="email" name="email">
    <input type="number" name="number" min="0" max="100">
    <input type="range" name="range" min="0" max="10">
    <input type="date" name="date">
    <input type="time" name="time">
    <input type="search" name="search">
    <input type="url" name="url">
    <input type="tel" name="tel">
    <input type="color" name="color">
    <input type="file" name="file" accept="image/*">
</form>

Additional HTML Input Attributes

In addition to the standard type, name, and placeholder attributes, the <input> tag supports several additional attributes that can control its appearance and behavior.

  • size: The size attribute specifies the visible width of an input element in characters.
  • readonly: With the readonly attribute, you can make an input field read-only. Note, however, that users can still copy read-only values.
  • disabled: By disabling an input field with disabled, you can make it impossible for users to interact with it.
  • maxlength: The maxlength attribute limits the number of characters of input elements that accept text.
  • autocomplete: With autocomplete, you can allow the browser to automatically complete input values based on previously entered values. The attribute value can be on or off, or a description of the auto-completion value.
  • required: Makes the input field mandatory for form submission.
  • pattern: Defines a regular expression pattern to validate the input value.
  • min: Using the min attribute, you can define a lower bound for numerical input values.
  • max: With the max attribute, you can define an upper bound for numerical input values.

<form>
    <label for="phone">Phone Number (Read-only):</label>
    <input type="tel" id="phone" name="phone" value="123-456-7890" readonly>

    <label for="username">Username (Max 15 characters):</label>
    <input type="text" id="username" name="username" maxlength="15" placeholder="Enter your username">

    <label for="age">Age (Disabled field):</label>
    <input type="number" id="age" name="age" min="18" max="100" value="25" disabled>

    <label for="zip">ZIP Code (Pattern validation):</label>
    <input type="text" id="zip" name="zip" pattern="\d{5}-\d{4}" placeholder="12345-6789" required>

    <label for="color">Favorite Color (Autocomplete):</label>
    <input type="color" id="color" name="favcolor" autocomplete="on">

    <input type="submit" value="Submit">
</form>

Client-Side Validation of HTML Forms

With attributes like required, pattern, min, and max, HTML provides built-in validation for form inputs. By using client-side form validation, you can catch invalid inputs before you send them to a server.

For example, you can add an empty required attribute to mark an input element as required within a form. Also, you can use the pattern attribute to validate a ZIP code.

<form>
    <input type="text" name="zipcode" pattern="\\d{5}-\\d{4}" required placeholder="Enter ZIP code (e.g., 12345-6789)">
    <input type="submit" value="Submit">
</form>

However, client-side validation is easy to bypass. As a security measure, validating form submissions on the server side as well is important.

Styling Input Fields

You can use CSS to style <input> elements to match your website's design. In particular, properties like border, background, and box-shadow can enhance the visual appearance of input fields.

input[type="text"] {
    border: 1px solid #ccc;
    background-color: #f8f8f8;
    box-shadow: inset 0 1px 3px #ddd;
}

Dynamic Input Fields

Finally, you can embed JavaScript to interact with <input> elements. With JavaScript, you can create dynamic behaviors, like displaying a file preview or validating input in real-time.

<script>
document.getElementById('imageFile').onchange = function(evt) {
    var files = evt.target.files;
    for (var i = 0, f; f = files[i]; i++) {
        if (!f.type.match('image.*')) {
            continue;
        }
        var reader = new FileReader();
        reader.onload = (function(theFile) {
            return function(e) {
                document.getElementById('preview').src = e.target.result;
            };
        })(f);
        reader.readAsDataURL(f);
    }
}
</script>
<input type="file" id="imageFile">
<img id="preview" src="" alt="Image preview...">
Learn HTML for Free
Start learning now
button icon
To advance beyond this tutorial and learn HTML by doing, try the interactive experience of Mimo. Whether you're starting from scratch or brushing up your coding skills, Mimo helps you take your coding journey above and beyond.

Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.

You can code, too.

© 2024 Mimo GmbH