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">

7

2 Answers 2

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.

2
  • 4
    In the modern era, we should not be encouraging the use of inline event handlers. Also, this question is a duplicate of many, many others. Commented Apr 18, 2017 at 19:01
  • It depends how the Inline event handlers are being used. For learning it's ok to use this code. Also, in this question OP said that it didn't work. That means the OP is asking about why the alert didn't work. Commented Apr 18, 2017 at 19:06
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()"/>

0

Not the answer you're looking for? Browse other questions tagged or ask your own question.