Reputation: 386
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
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
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);
Upvotes: 3
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
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