Reputation:
Say that I have an input with the type "checkbox"
<input type='checkbox' id='checker'>
I need to be able to detect instantly whether this box is checked, without a button click or function call. Checking and unchecking the box will lighten or darken text. How do I constantly check whether the box is unchecked or not IN VANILLA JAVASCRIPT? I need to be able to do this, preferably without an infinite for-loop that'll crash the page. I know the method for it
var value=document.getElementById('checker').checked;
but I need a way to constantly see whether it has been checked or not without reloading the page using vanilla javascript. Please help!
EDIT: I am also considering using two radio buttons, one with value true and the other with value false, but I still need a way of seeing which one is checked.
Upvotes: 0
Views: 253
Reputation: 19485
document.addEventListener('click', function(e) {
if (e.target.nodeName == 'INPUT' && e.target.type == 'checkbox' && e.target.checked) {
alert('Checked!');
}
});
<input type="checkbox" />
e.target.nodeName
returns the tag name of the clicked elemente.target.type
returns its typee.target.checked
returns whether the clicked element became checkedWorks for all checkboxes on the page (you can also check e.taget.id
whether you have the right one).
In this case a change
event listener is more appropriate, as you can click on a radio button without changing it.
document.addEventListener('change', function(e) {
if (e.target.nodeName == 'INPUT' && e.target.type == 'radio' && e.target.checked) {
alert(e.target.id); // returns either `yes` or `no`.
}
});
<label><input id="yes" name="radio0" type="radio" />Yes</label>
<label><input id="no" name="radio0" type="radio" />No</label>
If you attach the event listeners to document
rather than to a specific input
, there are a few advantages:
addEventListener('DOMContentLoaded',function(){})
or something similar. It doesn’t matter, whether the content has loaded, this event will also fire and the correct target will always be provided.It is a bit advanced, though. If you want to change the elements next to the input boxes, no matter which input box has been clicked, you’ll have to do this with nextElementSibling
, previousElementSibling
, parentNode
, children
, etc.
Upvotes: 0
Reputation: 9550
Check the working demo: http://jsfiddle.net/rrath8tg/1/:
// checkbox is a reference to the element
checkbox.onchange = function() {
if(this.checked) {
// do something when checked
}
};
Or onchange
on checkbox element.
Upvotes: 2
Reputation: 777
You could use just CSS providing that the text you want to change is on the same level in the DOM:
HTML:
<input type="checkbox" id="checker">
<span id="sometext">Lorem ipsum...</span>
CSS:
input#checker:checked + span#sometext {
color:#ff0000; /* Red - highlighted */
}
Upvotes: 1