10 Hidden Truths of the <input> Element

Explore intriguing aspects that lie beneath the surface of the <input> element.

Zachary Lee
Bits and Pieces
Published in
7 min readMay 30, 2023

--

Photo by Sigmund on Unsplash

As web developers, we often work with various HTML elements to create interactive and dynamic user interfaces. One of the most commonly used elements is the <input> element, which allows users to input data. While most of us are familiar with its basic attributes like type, value, and placeholder, there are several lesser-known attributes that can enhance our understanding and utilization of this versatile element.

1. defaultValue

The defaultValue attribute of the <input> element allows us to access or set the default value initially specified in the HTML that created the object. It represents the value defined in the value attribute of the element. Let's take a look at an example:

<input type="text" value="Hello, World!">

In the above code snippet, the defaultValue attribute will initially reflect the value defined in the value attribute, which is "Hello, World!". We can access and modify the value of the input element using JavaScript, as shown below:

const input = document.querySelector('input');
console.log(input.value); // Output: "Hello, World!"

input.value = 'New value';
console.log(input.value); // Output: "New value"
console.log(input.defaultValue); // Output: "Hello, World!"

By using the defaultValue attribute, we can retrieve the original value of the input element even after modifying its current value.

2. multiple

The multiple attribute is specific to file input elements (<input type="file">) and allows users to select multiple files for upload. When the multiple attribute is present, the file input will accept more than one file selection from the user. Here's an example:

<input type="file" multiple>

With the multiple attribute, users can select multiple files either by holding down the Ctrl (or Command on macOS) key while selecting files or by using the Shift key to select a range of files.

To access the selected files programmatically, we can use the files property of the file input element. It returns a FileList object containing all the selected files:

const fileInput = document.querySelector('input[type="file"]');

fileInput.addEventListener('change', () => {
console.log(fileInput.files);
});

In the above code snippet, we listen for the change event on the file input element. When the user selects one or more files, the event handler retrieves the selected files through the files property and logs them to the console.

3. selectionStart, selectionEnd, and selectionDirection

The selectionStart, selectionEnd, and selectionDirection attributes of the <input> element enable us to determine and manipulate the selected text within an input field. These attributes are particularly useful when we need to perform actions based on the user's selection. Let's explore them in more detail:

  • selectionStart: This attribute returns the index of the first selected character within the input field. If no text is selected, it returns the index of the cursor position.
  • selectionEnd: This attribute returns the index of the last selected character within the input field. If no text is selected, it returns the same index as selectionStart.
  • selectionDirection: This attribute indicates the direction of the selection and can have one of three values: "forward", "backward", or "none". It determines whether the user selectedthe text from left to right ("forward"), from right to left ("backward"), or if there is no selection ("none").

To better understand these attributes, let’s consider an example where we have an input field and want to monitor the user’s selection:

<input type="text" id="myInput" value="Hello, World!">

We can use JavaScript to log the values of selectionStart, selectionEnd, and selectionDirection at regular intervals:

const input = document.getElementById('myInput');

setInterval(() => {
console.log(input.selectionStart);
console.log(input.selectionEnd);
console.log(input.selectionDirection);
}, 1000);

In the above code snippet, we retrieve the input element by its ID and set up an interval to log the selection attributes every second. When the user selects a portion of the input’s value, the respective attributes will reflect the selected range and direction.

By utilizing these attributes, we can perform various actions based on the user’s selection, such as extracting the selected text, applying formatting, or manipulating the selected portion of the input’s value.

4. step

The step attribute is applicable to number input elements (<input type="number">) and defines the increment or decrement step for the input's value. It restricts the values that users can enter or select within the input field. The step attribute accepts numeric values and can be either positive, negative, or zero. Let's examine an example:

<input type="number" step="5" min="0" max="100">

In the above code snippet, we have a number input that has a step value of 5. This means users can only select or enter values that are multiples of 5. Additionally, the min and max attributes specify the minimum and maximum allowed values, respectively.

By setting the step attribute, we ensure that the input's value adheres to the defined increment or decrement. For example, with a step of 5, the input will increment or decrement the value by 5 units when using the up or down arrows or other input methods.

The step attribute is particularly useful in situations where we want to restrict the input to specific intervals or ensure that the entered values align with a predefined scale.

5. indeterminate

The indeterminate attribute is a fascinating property of checkboxes, radio buttons, and progress elements. It introduces an additional visual state for checkboxes and indicates that they have no value. When set to true, it displays a dash in the checkbox instead of a checked or unchecked state. Let's see an example:

<input type="checkbox" />

<script>
const input = document.querySelector('input');
input.indeterminate = true;
</script>

In the above code snippet, the checkbox will be in an indeterminate state, represented by a dash. This state doesn’t affect the actual value of the checkbox.

6. autocomplete

The autocomplete attribute allows us to control the autofill behavior of an input field. Autofill is a feature provided by browsers that automatically fills in form fields with previously entered values. By using the autocomplete attribute, we can specify whether the browser should enable or disable autofill for a particular input field. Let's explore its usage:

<input type="text" autocomplete="off">

In the above code snippet, we set the autocomplete attribute to "off", which instructs the browser to disable autofill for this input field. This can be useful when dealing with sensitive information or when we want to provide a customized input experience.

The autocomplete attribute can also accept other values such as "on" or specific values related to different types of information. For example, we can use "name" for name fields, "email" for email fields, or "postal-code" for postal code fields to provide hints to the browser about the expected input.

It’s important to note that although we can use the autocomplete attribute to provide hints, the browser ultimately determines whether to autofill a field based on user preferences and previously entered data.

7. required

The required attribute is used to indicate that an input field must be filled out before submitting a form. When applied to an <input> element, it ensures that the user provides a value for that field. Here's an example:

<input type="text" required>

In the above code snippet, the required attribute is applied to a text input field. If the user tries to submit the form without entering any value in this field, the browser will prevent form submission and display an error message prompting the user to provide a value.

8. pattern

The pattern attribute allows us to specify a regular expression pattern that an input value must match in order to be considered valid. It is primarily used with text input fields and provides a client-side validation mechanism. Let's see an example:

<style>
input:valid {
background-color: palegreen;
}
input:invalid {
background-color: lightpink;
}
</style>
<form>
<input
type="text"
pattern="[A-Za-z]+"
title="Only alphabetical characters are allowed"
/>
<button>Submit</button>
</form>

In the above code snippet, the pattern attribute is set to [A-Za-z]+, which matches one or more alphabetical characters. The title attribute provides a descriptive error message that will be displayed if the user enters an invalid value.

When the user submits the form, the browser will automatically validate the input value against the specified pattern. If the value doesn’t match the pattern, an error message will be displayed, and the form submission will be prevented.

9. maxlength

The maxlength attribute specifies the maximum number of characters allowed in an input field. It can be applied to both text and password input fields. Here's an example:

<input type="text" maxlength="10">

In the above code snippet, the maxlength attribute is set to 10, meaning that the user can enter a maximum of 10 characters in the input field.

When the user tries to enter or paste more characters than the specified limit, the browser will prevent further input. This attribute is usefulfor enforcing length restrictions on input fields, such as limiting usernames, passwords, or other textual data.

It’s important to note that the maxlength attribute only restricts user input on the client side. Server-side validation is still necessary to ensure data integrity and security.

10. list and datalist

The list attribute, in combination with the <datalist> element, provides a way to create custom dropdown suggestions for text input fields. It allows us to associate an input field with a predefined list of options that users can choose from. Let's explore how it works:

<input type="text" list="fruits">
<datalist id="fruits">
<option value="Apple">
<option value="Banana">
<option value="Cherry">
<option value="Durian">
</datalist>

In the above code snippet, the list attribute of the input field is set to "fruits", which corresponds to the ID of the <datalist> element. The <datalist> element contains a list of <option> elements that represent the available options.

When the user interacts with the input field, they will see a dropdown with the suggested options from the <datalist> element. They can either select an option from the list or manually enter their own value.

Using the list and datalist attributes, we can provide a convenient autocomplete-like experience for users, suggesting relevant options based on their input.

Conclusion

In this article, we explored 10 hidden truths of the <input> element that can enhance our understanding and utilization of this fundamental HTML element. Happy coding!

Thanks for reading! Love these stories? Support me with a membership for monthly handpicked articles. Or join Medium via my link.

--

--