Milan Shah
Milan Shah

Reputation: 11

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.

Upvotes: 1

Views: 994

Answers (4)

Karl-Andr&#233; Gagnon
Karl-Andr&#233; Gagnon

Reputation: 33880

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

  1. You misspelled id on the DOM tag.

  2. 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);
        }
})

Upvotes: 1

A. Wolff
A. Wolff

Reputation: 74410

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);
});

Upvotes: 1

Broxzier
Broxzier

Reputation: 2949

This question has been asked before, and someone posted a detailed answer: https://stackoverflow.com/a/2204275/1745452

The jQuery API Documentation states that it should be working since the first verion. Perhaps you misspelled the selectors?

Upvotes: 0

Adil Shaikh
Adil Shaikh

Reputation: 44740

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

Upvotes: 3

Related Questions