Open In App

How to pre-select an input element when the page loads in HTML5?

Last Updated : 15 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we are going to pre-select an input element when the page loads i.e. the user doesn’t have to click the first text box to start writing on it. When the page is loaded the input is to be pre-selected and the user can start typing directly. This can be done by using the autofocus attribute. It is a boolean attribute that brings an element into focus and supports <button>, <input>, <select>, and <textarea> elements.

Approach:

  • Create a div for the HTML form.
  • We will make input elements inside a form of type text and add autofocus to the username.
  • On page load, we will see that username will be in focus, and we can directly start typing.

Syntax :

<input type="text" autofocus>

Example: In this example, we will see the use of an input element with its property for pre-selecting when the page loads.

HTML




<!DOCTYPE html>
<html lang="en">
<body>
    <h1> pre-select an input element </h1>
    <form>
        <label>Username:</label><br>
        <input type="text" name="username" autofocus>
        <br>
        <label>Email id:</label><br>
        <input type="text" name="email_id">
        <br><br>
        <input type="submit" value="Submit">
    </form>
</body>
</html>


Output:

Pre-select input element


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads