简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM