admin管理员组文章数量:1327660
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
本文标签: javascriptjquery if checkbox is checkedalert with result isn39t workingStack Overflow
版权声明:本文标题:javascript - jquery if checkbox is checked, alert with result isn't working - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742228510a2436777.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论