最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jquery if checkbox is checked, alert with result isn't working - Stack Overflow

programmeradmin4浏览0评论

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
Add a ment  | 

2 Answers 2

Reset to default 5

Here'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

发布评论

评论列表(0)

  1. 暂无评论