0

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">
Anant Kumar Singh
  • 68,309
  • 10
  • 50
  • 94
Amal
  • 75
  • 2
  • 11

2 Answers2

1

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.

Anant Kumar Singh
  • 68,309
  • 10
  • 50
  • 94
0

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()"/>
Abhinav Galodha
  • 8,555
  • 2
  • 31
  • 39