How to Set Default HTML Form Focus Without Javascript
In this tutorial, you’ll see how to set the default HTML form focus. This can be done without Javascript. For that, use the HTML “autofocus” attribute.
Solutions with HTML
It is possible to set a default input focus on an HTML form without Javascript. This can be done in HTML5, as it allows us to use the autofocus attribute on form control elements (such as <input>, <textarea>, or <button>).
Example of setting a default form focus:
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
</head>
<body>
<input type="text" name="myInput" autofocus />
</body>
</html>Result
<div class="demo p-2.5 mt-1 mb-5 not-prose"> <input autofocus="" name="myInput" type="text">``</input> </div>In the example above, we used one <input> element and added the <span class="attribute">autofocus</span> attribute to it.
Let’s see another example, where we use a few <input> elements, and set the <span class="attribute">autofocus</span> attribute only on one of them.
Example of setting focus only for one <input> element:
<!DOCTYPE html>
<html>
<head>
<title>Title of the document.</title>
<style>
div {
margin-bottom: 10px;
}
label {
display: inline-block;
width: 70px;
}
</style>
</head>
<body>
<h1>Example</h1>
<form action="/form/submit" method="get">
<div>
<label for="name">Name:</label>
<input type="text" id="name" name="name" autofocus />
</div>
<div>
<label for="surname">Surname:</label>
<input type="text" id="surname" name="surname" />
</div>
<div>
<label for="year">Year:</label>
<input type="number" id="year" name="year" value="2020" disabled />
</div>
<input type="submit" />
</form>
</body>
</html>For the first <input>, we set the <span class="attribute">autofocus</span> attribute, and for the third <input>, we set the disabled attribute. Here, we also used some CSS and set the margin-bottom property for the <div> element, and specified the display property with the “inline-block” value and width property for the <label> element. Note: Only one element per document should use the autofocus attribute to avoid focus conflicts.