EN
JavaScript - focus HTML input field on label click
3 points
In this article, we would like to show you how to focus input field on label click using JavaScript.
Quick solution:
xxxxxxxxxx
1
<div>
2
<span onclick="this.nextElementSibling.focus()">Click the label to focus input</span>
3
<input type="text"/>
4
</div>
or:
xxxxxxxxxx
1
<div>
2
<input type="text"/>
3
<span onclick="this.previousElementSibling.focus()">Click the label to focus input</span>
4
</div>
By using JavaScript ,we are able to get input
element focus by calling its focus()
method.
It is good to consider 2 cases:
In this section, we use nextElementSibling
property that lets to get next element to the label.
xxxxxxxxxx
1
2
<html>
3
<body>
4
<div>
5
<span onclick="this.nextElementSibling.focus()">Field name</span>
6
<input type="text"/>
7
</div>
8
</body>
9
</html>
In this section, we use previousElementSibling
property that lets to get previous element to the label.
xxxxxxxxxx
1
2
<html>
3
<body>
4
<div>
5
<input type="text"/>
6
<span onclick="this.previousElementSibling.focus()">Field name</span>
7
</div>
8
</body>
9
</html>