Languages
[Edit]
EN

HTML - focus input field on label click

0 points
Created by:
Marley-Marks
712

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

Quick solution:

// ONLINE-RUNNER:browser;

<label for="field">Field name:</label>
<input type="text" id="field"/>

or:

// ONLINE-RUNNER:browser;

<label>
  <span>Field name:</span>
  <input type="text"/>
</label>

 

Practical example

In this example, we create the label element that we can click to focus the input field. The key is that the label element describing the input  is bound to it using the id - for relation.

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<body>
  <label for="field">Field name:</label>
  <input type="text" id="field"/>
</body>
</html>

Alternative solution

In this section, we present an alternative solution where input element is wrapped with label. The solution works the same as the first one but we don't need to specify id attribute.

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<body>
  <label>
    <span>Field name:</span>
    <input type="text"/>
  </label>
</body>
</html>

 

See also

  1. JavaScript - focus HTML input field on label click

References

  1. <label>: The Input Label element - HTML | MDN
  2. <input type="text"> - HTML | 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