Reputation: 75
I'm trying to test if a checkbox is checked or no I found this solution but I'm getting nothing
if(document.getElementById('checkbox-1').checked) {
alert("checked");
}
<input id="checkbox-1" class="checkbox-custom" name="checkbox-1" type="checkbox">
Upvotes: 0
Views: 172
Reputation: 72269
You have to trigger click even of check-box which will call a function that do the desired task.
Example how you can do it:-
function checkClick(){
if(document.getElementById('checkbox-1').checked) {
alert("checked");
}
}
<input id="checkbox-1" class="checkbox-custom" name="checkbox-1" type="checkbox" onclick="checkClick()"> <!-- trigger click event using onclick and calling a function -->
Note:- you can change function name according to your wish.
Upvotes: 1
Reputation: 9928
You need to Trigger the event. For checkbox, the onchange
event would fire anytime the value changes. So, you need to hook up a event handler which can be a function reference or function declaration like onchange="checkboxChanged()
function checkboxChanged(){
if(document.getElementById('checkbox-1').checked) {
alert('checked');
}
else{
alert('Not checked');
}
}
<input id="checkbox-1" class="checkbox-custom" name="checkbox-1" type="checkbox" onchange="checkboxChanged()"/>
Upvotes: 0