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?
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)