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
  • 169,008
  • 28
  • 173
  • 236
Ethan
  • 3,410
  • 1
  • 28
  • 49

1 Answers1

5

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
  • 3,410
  • 1
  • 28
  • 49