开发者

Jquery validate checkbox confused?

Any idea why this code keeps saying on and doesn't work how expected ?

$('#myCheckbox').click(function() {
    if ( $('#myCheckbox').attr('checked')) {
        alert开发者_开发问答("on");
    } else {
        alert("off");
    }
});

example here

http://jsfiddle.net/BFf5H/


1) Use prop added to jQuery 1.6 (I guess)

$('#myCheckbox').click(function() {
    if ( $(this).prop('checked')) {
        alert("on");
    } else {
        alert("off");
    }
});

2)Use is to check the state

Try this:

$('#myCheckbox').click(function() {
        if ( $(this).is(':checked')) {
            alert("on");
        } else {
            alert("off");
        }
    });

Working example: http://jsfiddle.net/BFf5H/2/

3) @Felix's suggestion Try this:

$('#myCheckbox').click(function() {
        if ( this.checked) {
            alert("on");
        } else {
            alert("off");
        }
    });

EDIT:

As per the URL provided by OP alternate solution:

$(".styled").change(function(){
  if(this.checked){
   alert("On");
  } else {
   alert("Off");
  }
})


Try:

$('#myCheckbox').click(function() {
    if ( $(this).is(':checked')) {
        alert("on");
    } else {
        alert("off");
    }
});


<html>

    <head>

        <script src="http://www.google.com/jsapi" type="text/javascript"></script>
        <script type="text/javascript">google.load("jquery", "1");</script>
        <script type="text/javascript">

            $(document).ready(
                function() 
                {
                    $('#myCheckbox').click(
                        function() 
                        {   
                            if( $(this).attr('checked') == 'checked' )
                            {
                                alert('yes');
                            }
                            else
                            {
                                alert('no');
                            }
                        }
                    );
                }
            );

        </script>

    </head>

    <body>

        <input type="checkbox" checked="checked" id="myCheckbox" />

    </body>

</html>

Download this solution

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜