开发者

jquery if checkbox is checked, alert with result isn't working

开发者 https://www.devze.com 2023-02-19 06:24 出处:网络
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 \"ch

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
      开发者_JAVA技巧      }

        });
    });


<input type="checkbox" id="c2" name="c2" ></input>


<img src="image.png" id="midmenusubmit" />


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

精彩评论

暂无评论...
验证码 换一张
取 消