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
    Duplicate stackoverflow.com/questions/2204250/… Commented Apr 18, 2017 at 18:51
  • 2
    Possible duplicate of Check if checkbox is checked with jQuery Commented Apr 18, 2017 at 18:52
  • 4
    there isn't really any 'event' to trigger that JavaScript. Maybe that should happen when the checkbox is checked or not? on 'change' maybe? Commented Apr 18, 2017 at 18:52
  • The OP doesn't actually ask for event capturing, just how to test the checked state Commented Apr 18, 2017 at 18:59
  • @ProgrammerV5 those are jQuery answers now native JS Commented Apr 19, 2017 at 14:08

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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.
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.
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()"/>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.