This content originally appeared on CodeSource.io and was authored by Deven
In this article, you will learn about how to focus an input field by using JavaScript.
JavaScript is a text-based programming language that is used both on the client-side and server-side. You can bring activity to your web page and make web pages interactive. Input focused is one kind of interactivity that you can use on your web page via JavaScript.
To focus an input field in JavaScript you can simply call the .focus() method. It will give focus to an HTML element and it does not take any parameter. Follow the below code example to focus an input field
HTML Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Input Focused</title>
</head>
<body>
<div id="container">
<label for="name">Name:</label>
<input type="text" id="name">
</div>
<button id="submit">Focus</button>
<script src="main.js"></script>
</body>
</html>
In the HTML file, we take an input field and a button named Focus and link our JavaScript file.
JavaScript Code:
document.getElementById("submit").onclick = function() {
document.getElementById("name").focus();
}
In this file, we write JavaScript login and call .focus() method to focus our input field. Let’s see the output below:
When we click on the focus button the input field gets focused and sets the element as the active element in the current document.
This is how you can focus an input field by using JavaScript .focus() method.
The post How to do input focused in JavaScript appeared first on CodeSource.io.
This content originally appeared on CodeSource.io and was authored by Deven
Deven | Sciencx (2021-12-02T04:04:55+00:00) How to do input focused in JavaScript. Retrieved from https://www.scien.cx/2021/12/02/how-to-do-input-focused-in-javascript/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.