hungariandude
hungariandude

Reputation: 386

If checkbox checked, instantly alert

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!

Upvotes: 0

Views: 15043

Answers (4)

m4n0
m4n0

Reputation: 32275

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>

Upvotes: 2

Tushar
Tushar

Reputation: 87203

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

Upvotes: 3

www.diazis.com
www.diazis.com

Reputation: 96

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>

Upvotes: 0

Guruprasad J Rao
Guruprasad J Rao

Reputation: 29683

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"); 
     } 
}

Upvotes: 0

Related Questions