1

I have seen similar questions such as "How do I toggle an element's class in pure JavaScript?", but this question refers to attributes instead.

I have a checkbox like so:

<span class="newsletter-checkbox">
  <input type="checkbox" name="newsletter" id="newsletter" checked> Sign up to the newsletter as well - recieve new posts in your inbox
</span>

How do I make it so that when anywhere in .newsletter-checkbox (including the text) is clicked, it toggles the checkbox checked attribute?

mplungjan
  • 155,085
  • 27
  • 166
  • 222
Ethan
  • 2,734
  • 1
  • 20
  • 43

1 Answers1

3

Simply use this:

function toggleCheckbox() {
  var checkbox = document.getElementById('newsletter');
  checkbox.checked = !checkbox.checked;
}
<span class="newsletter-checkbox" onclick="toggleCheckbox()"><input type="checkbox" name="newsletter" id="newsletter" checked> Sign up to the newsletter as well - recieve new posts in your inbox</span>

(based off Toggle a boolean in javascript)

Ethan
  • 2,734
  • 1
  • 20
  • 43