0

So, my goal is this: if the checkbox is checked by the user, do something (let's say just an alert). Here's my code, that is not working:

function validate() {
    if (document.getElementById('LetterNeed').checked) {
        alert("checked");
    } else {
        alert("You didn't check it! Let me check it for you.");
    }
}    

<input type="checkbox" name="LetterNeed" id="LetterNeed">Not important</span>

Thanks for your help!

3
  • where are you calling the validate() function?
    – Varun
    Jun 22, 2015 at 12:24
  • 1
  • If you wrap the checkbox in a label element or connect the two with the "for" attribute of the label, you can check/uncheck it by clicking on either the box or the label, which provides a much larger target to click/tap on.
    – enhzflep
    Jun 22, 2015 at 12:26

4 Answers 4

3

Call the validate function on change of the checkbox state.

<input type="checkbox" name="LetterNeed" id="LetterNeed" onchange="return validate()">Not important</span>
//                                                       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^

OR

document.getElementById('LetterNeed').addEventListener('change', validate);

DEMO

2

Old Approach

Call the validate() function in the <input> tag

function validate() {
    if (document.getElementById('LetterNeed').checked) {
        alert("checked");
    } else {
        alert("You didn't check it! Let me check it for you.");
    }
}    
<input type="checkbox" name="LetterNeed" id="LetterNeed" onclick="validate()">Not important</span>

Event Handling approach

function validate() {
  if (this.checked) {
    alert("checked");
  } else {
    alert("You didn't check it! Let me check it for you.");
  }
}

document.getElementById('LetterNeed').addEventListener('click', validate);
<input type="checkbox" name="LetterNeed" id="LetterNeed"><span>Not important</span>

0

on the other hand you can add eventlistener on DOMContentLoaded as below:

document.addEventListener('DOMContentLoaded', function () {
      document.querySelector('#LetterNeed').addEventListener('change', validate);
});

A function to validate

function validate(e){
     if(e.target.checked)
     { 
        alert("Checked"); 
     } 
     else{ 
        alert("Not checked"); 
     } 
}
1
  • 1
    Within the listener, this will reference the element so forget e.target and use this. ;-)
    – RobG
    Jun 22, 2015 at 12:51
0

try these changes :

function validate(aCheckBox) {
  if (aCheckBox.checked) {
    alert("checked");
  } else {
    alert("You didn't check it! Let me check it for you.");
  }
}    

<input type="checkbox" name="LetterNeed" id="LetterNeed" onclick="validate(this)">Not important</input>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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