I’m using jQuery and trying to check if checkbox is checked style. Here’s my current code:
<input id="remember" name="remember" type="checkbox" onclick="validate()" />
function validate() {
if (remember.checked == 1) {
alert("checked");
} else {
alert("You didn't check it! Let me check it for you.");
}
}
But it doesn’t seem to work. After some debugging, I realized the issue was a naming conflict. My fieldcontain
div was also named ‘remember’. Once I changed that, it worked. Any cleaner way to handle this?
Below is the most direct way with no-library. I use this when I want to keep things lightweight for performance in mobile web apps.
function validate() {
const checkbox = document.getElementById('remember');
if (checkbox.checked) {
alert("Checked!");
} else {
alert("Not checked!");
}
}
On jQuery Mobile projects, this blends perfectly with form stylings and auto-inits, and it avoids native quirks across devices.
function validate() {
if ($('#remember').is(':checked')) {
alert("Checked!");
} else {
alert("Not checked!");
}
}
You can add event listener instead of onclick
in HTML :
document.getElementById('remember').addEventListener('change', function () {
if (this.checked) {
alert("Checked!");
} else {
alert("Not checked!");
}
});
My tip: I started using this to keep HTML clean and separate logic from structure—makes future maintenance way easier, especially on larger forms.