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">
Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98
Amal
  • 75
  • 1
  • 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.

Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98
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
  • 9,293
  • 2
  • 31
  • 41