I can't figure out what's wrong with this code. It is supposed to check if a checkbox is checked, and alert "checked" if it is and "not checked" if it's not. However it keeps returning the "checked" result every time.
$(document).ready(function () {
$('#midmenusubmit').click(function () {
if ($('input:c2:checked').val() != undefined) {
alert("checked");
//checked
}
else {
alert("not checked");
//not checked
}
});
});
<input type="checkbox" id="c2" name="c2" ></input>
<img src="image.png" id="midmenusubmit" />
I can't figure out what's wrong with this code. It is supposed to check if a checkbox is checked, and alert "checked" if it is and "not checked" if it's not. However it keeps returning the "checked" result every time.
$(document).ready(function () {
$('#midmenusubmit').click(function () {
if ($('input:c2:checked').val() != undefined) {
alert("checked");
//checked
}
else {
alert("not checked");
//not checked
}
});
});
<input type="checkbox" id="c2" name="c2" ></input>
<img src="image.png" id="midmenusubmit" />
Share
Improve this question
edited Mar 21, 2011 at 20:27
BoltClock
725k165 gold badges1.4k silver badges1.4k bronze badges
asked Mar 21, 2011 at 20:24
korbenkorben
5371 gold badge7 silver badges18 bronze badges
1
-
Your selector is wrong, it should be
#c2
not:c2
. – BoltClock Commented Mar 21, 2011 at 20:27
2 Answers
Reset to default 5Here's a more succinct way to check the state of your checkbox:
if ($('input#c2').is(':checked')) {
Better to use
$('input:c2:checked').length > 0
or
$('input:c2').is(':checked') // returns true or false
The .val() is looking for a value on the input element and never finds it hence it always being undefined