Exploring the Instance Methods of HTMLInputElement
Introduction:
In this Medium article, we’ll be diving deep into a core element of web development: the HTMLInputElement. This object, part of the broader Web API, is crucial for managing user input on webpages, providing functionalities that range from simple text boxes to intricate file upload systems.
First, let’s clarify what an HTMLInputElement is. It corresponds to the <input> element in HTML, and is designed to capture and handle user data. This data can be typed text, selected options, or uploaded files, depending on the type attribute of the input element.
To facilitate interaction with the <input> element, the HTMLInputElement interface in JavaScript provides a series of instance methods. These methods are functions that perform specific tasks, which are attached to each instance of HTMLInputElement. For example, you might use the checkValidity() method to confirm whether the user’s input satisfies the specified validation constraints.
In the following sections, we will explore these methods in detail, showing you how they work, where they can be applied, and why they are essential to crafting an interactive, user-friendly webpage. We’ll cover methods such as select(), setSelectionRange(), setCustomValidity(), and many more. By the end of this article, you will have a deep understanding of the instance methods of HTMLInputElement and be able to use them effectively in your web development projects.
So, whether you are a seasoned developer looking for a refresher, or a novice stepping into the web development world, this comprehensive guide is sure to provide you with valuable insights into the powerful HTMLInputElement interface and its instance methods.
Let’s dive in!
The <input>
HTML element is used to create interactive controls for web-based forms in order to accept data from the user.
Let’s now focus on Instance methods of HTMLInputElement:
Instance Methods of HTMLInputElement:
- checkValidity()
This method will return a boolean which checks the element’s value is valid or invalid. This method additionally fires the invalid event on the element if the value is invalid.
Example:
<!DOCTYPE html>
<html>
<head>
<title>checkValidity() Example</title>
</head>
<body>
<form>
<label for="name">Name:</label>
<input type="text" id="name" required pattern="[A-Za-z]+" minlength="2" maxlength="30">
<button type="button" onclick="validateInput()">Submit</button>
</form>
<script>
function validateInput() {
var nameInput = document.getElementById("name");
if (nameInput.checkValidity()) {
alert("Input is valid!");
// Perform further actions or submit the form
} else {
alert("Input is invalid!");
// Optionally, display custom error messages or highlight the invalid field
}
}
</script>
</body>
</html>
Output:
2. reportValidity()
The HTMLInputElement interface’s reportValidity() method carries out the same validity checks as its checkValidity() counterpart. This function notifies the user of the issue if the value is invalid and fires the invalid event on the element (if the event isn’t cancelled).
Example:
<!DOCTYPE html>
<html>
<head>
<title>reportValidity() Example</title>
</head>
<body>
<form>
<label for="email">Email:</label>
<input type="email" id="email" required>
<button type="button" onclick="validateInput()">Submit</button>
</form>
<script>
function validateInput() {
var emailInput = document.getElementById("email");
if (emailInput.checkValidity()) {
alert("Input is valid!");
// Perform further actions or submit the form
} else {
emailInput.reportValidity();
// The error message will be displayed automatically
}
}
</script>
</body>
</html>
Output:
Error Output:
3.setCustomValidity()
This method will set a custom validity message for the element.
Example:
<!DOCTYPE html>
<html>
<head>
<title>Custom Validation Example</title>
<script>
function validateInput() {
var input = document.getElementById('myInput');
var value = input.value;
if (value.length < 5) {
input.setCustomValidity('Input must be at least 5 characters long.');
} else {
input.setCustomValidity('');
}
}
</script>
</head>
<body>
<form>
<input type="text" id="myInput" required oninput="validateInput()">
<input type="submit" value="Submit">
</form>
</body>
</html>
It will set the user defined validity message instead of built-in messages.
Output:
4.select()
The HTMLInputElement.select() method selects all the text in a <textarea> element or in an <input> element that includes a text field.
Example:
<!DOCTYPE html>
<html>
<head>
<title>Select Example</title>
<script>
function selectInput() {
var input = document.getElementById('myInput');
input.select();
}
</script>
</head>
<body>
<input type="text" id="myInput" value="Hello, world!">
<button onclick="selectInput()">Select Input</button>
</body>
</html>
This will highlight the entire text content of the input field, making it easier for the user to modify or copy the text.
Output:
5. setRangeText()
The HTMLInputElement.setRangeText() method substitutes a new string for a range of text in an input or textarea element.
Syntax: element.setRangeText(replacement, start, end, [selectionMode]);
i) ‘replacement’: The text that will replace the selected range.
ii) ‘start’: The index position at which to start replacing the text.
iii) ‘end’: The index position at which to end replacing the text.
iv) ‘selectionMode’ (optional): Specifies how the text selection should be handled. It can have one of the following values: “select”, “start”, “end”, or “preserve”.
Example:
<!DOCTYPE html>
<html>
<head>
<title>setRangeText Example</title>
<script>
function replaceText() {
var input = document.getElementById('myInput');
var startIndex = input.selectionStart;
var endIndex = input.selectionEnd;
var replacementText = 'New Text';
input.setRangeText(replacementText, startIndex, endIndex, 'start');
}
</script>
</head>
<body>
<input type="text" id="myInput" value="Hello, world!">
<button onclick="replaceText()">Replace Text</button>
</body>
</html>
Output:
6. setSelectionRange()
The setSelectionRange() method is a built-in method in HTML input elements that allows you to programmatically set the selection range of text within the input field.
Syntax: element.setSelectionRange(start, end, [direction]);
i) ‘start’: The index position at which the selection starts.
ii) ‘end’: The index position at which the selection ends.
iii) ‘direction’ (optional): Specifies the direction in which the selection is extended. It can have one of the following values: “forward”, “backward, or “none”.
Example:
<!DOCTYPE html>
<html>
<head>
<title>setSelectionRange Example</title>
<script>
function selectRange() {
var input = document.getElementById('myInput');
var startIndex = 6;
var endIndex = 11;
input.setSelectionRange(startIndex, endIndex);
input.focus();
}
</script>
</head>
<body>
<input type="text" id="myInput" value="Hello, world!">
<button onclick="selectRange()">Select Range</button>
</body>
</html>
This will selects the specified indices of the text in the <input> or <textarea> element.
Output:
7. showPicker()
The HTMLInputElement.showPicker() method displays the browser picker for an input element. It is a way to show a browser picker for <input> elements with these types: “date”, “month”, “week”, “time”, “datetime-local”, “color”, and “file”.
<!DOCTYPE html>
<html>
<head>
<title>HTMLInputElement.showPicker()</title>
</head>
<body>
<input type="date" id="dateInput">
<button onclick="showPicker()">Show Picker</button>
<script>
const dateInput = document.getElementById("dateInput");
const showPicker = () => {
dateInput.showPicker();
};
document.getElementById("showPickerButton").addEventListener("click", showPicker);
</script>
</body>
</html>
This will show a date picker along with the input element.
Output:
Conclusion:
Instant methods of the HTML input element provide efficient and interactive ways to handle user input in real-time. These methods allow developers to incorporate dynamic functionality and improve the user experience of web applications.
About the Author:
Abirami is a software developer with a keen eye for efficient code design. Her exceptional communication skills and ability to work collaboratively make her an invaluable team member in delivering successful software solutions.
About CodeStax.Ai
At CodeStax.Ai, we stand at the nexus of innovation and enterprise solutions, offering technology partnerships that empower businesses to drive efficiency, innovation, and growth, harnessing the transformative power of no-code platforms and advanced AI integrations.
But the real magic? It’s our tech tribe behind the scenes. If you’ve got a knack for innovation and a passion for redefining the norm, we’ve got the perfect tech playground for you. CodeStax.Ai offers more than a job — it’s a journey into the very heart of what’s next. Join us, and be part of the revolution that’s redefining the enterprise tech landscape.