is :checked not working while using Jquery 1.7

Look at this simple code


html

<input type="checkbox" id="check" >&nbsp;<span id="rm">Remember
me</span> <span id="ok">Okay!</span>

css

#ok{
position:absolute;
font:italic bold 14px century;
color:green;
margin-left:3px;
margin-top:2px;
display:inline-block;
opacity:0;
}

Jquery

if($('#check').is(":checked"))
    {
    $("#ok").css("opacity",1);
    }

http://jsfiddle.net/milanshah93/4Hf9T/

It is not working when I check the box.


Your checkbox was not checked on page load. although you can do something like this -

$("#check").on('change', function () {
    if ($(this).is(":checked")) {
        $("#ok").css("opacity", 1);
    }
    else{
     $("#ok").css("opacity", 0);
    }
});

DEMO


This is a working jsfiddle : http://jsfiddle.net/4Hf9T/14/

<input type="checkbox" id="check">&nbsp;<span id="rm">Remember me</span>

<span id="ok">Okay!</span>

JS code:

$('#check').on('change',function(){
    if(this.checked)
        $("#ok").css("opacity", 1);
    else 
        $("#ok").css("opacity", 0);
});

No it is working, but your code is not for those 2 reasons.

  • You misspelled id on the DOM tag.

  • You have no event listener. You code is running on window load and doesnt check after that. You need to add a binding like change .

  • Here the proof : http://jsfiddle.net/4Hf9T/13/

    $('#check').change(function(){
        if($(this).is(":checked"))
            {
            $("#ok").css("opacity",1);
            }
        else if(!$(this).is(":checked")) // "if" not needed, just showing that you can check if it is not checked.
            {
            $("#ok").css("opacity",0);
            }
    })
    
    链接地址: http://www.djcxy.com/p/55994.html

    上一篇: 获取复选框是否被选中或不在jquery / ES6中

    下一篇: 是:检查不工作,而使用Jquery 1.7