Languages
[Edit]
EN

JavaScript - select checkbox on click on related text

0 points
Created by:
nickkk0
647

In this article, we would like to show you how to select and unselect checkbox on click on related text using JavaScript.

Quick solution:

// ONLINE-RUNNER:browser;

<div>
  <input type="checkbox"/>
  <span onclick="this.previousElementSibling.click();">Click here to check input</span>
</div>

 

Practical example

In this example, we simulate a click event on the previousElementSibling property of a label (span element) that is right after the input that we want to check/uncheck.

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<body>
  <div>
    <input type="checkbox"/>
    <span onclick="this.previousElementSibling.click();">Click here to check input</span>
  </div>
</body>
</html>

See also

  1. HTML - select checkbox on click on related text

References

  1. Element.previousElementSibling - Web APIs | MDN
  2. HTMLElement.click() - Web APIs | MDN

Alternative titles

  1. JavaScript - select checkbox input on label click
  2. JavaScript - select and unselect checkbox on click on related text
  3. JavaScript - check / uncheck checkbox on click on related text
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