Languages
[Edit]
EN

JavaScript - focus HTML input field on label click

3 points
Created by:
user4838
698

In this article, we would like to show you how to focus input field on label click using JavaScript.

Quick solution:

// ONLINE-RUNNER:browser;

<div>
  <span onclick="this.nextElementSibling.focus()">Click the label to focus input</span>
  <input type="text"/>
</div>

or:

// ONLINE-RUNNER:browser;

<div>
  <input type="text"/>
  <span onclick="this.previousElementSibling.focus()">Click the label to focus input</span>
</div>

 

Practical examples

By using JavaScript ,we are able to get input element focus by calling its focus() method.

It is good to consider 2 cases:

1. label before input

In this section, we use nextElementSibling property that lets to get next element to the label.

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<body>
  <div>
    <span onclick="this.nextElementSibling.focus()">Field name</span>
    <input type="text"/>
  </div>
</body>
</html>

2. label after input

In this section, we use previousElementSibling property that lets to get previous element to the label.

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<body>
  <div>
    <input type="text"/>
    <span onclick="this.previousElementSibling.focus()">Field name</span>
  </div>
</body>
</html>

 

See also

  1. HTML - focus input field on label click

References

  1. Element.nextElementSibling - Web APIs | MDN
  2. Element.previousElementSibling - Web APIs | MDN
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join