1

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.

Sam
  • 7,252
  • 16
  • 46
  • 65
Milan Shah
  • 11
  • 1
  • It works for me: http://jsfiddle.net/4Hf9T/10/ you replaced `id` with `is`, and the input has to be checked initially to get the class. What you really need is a change event. – Kevin B May 14 '13 at 14:03
  • `if ( document.getElementById('check').checked ) { ... }` – adeneo May 14 '13 at 14:03

4 Answers4

3

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

Adil Shaikh
  • 44,509
  • 17
  • 89
  • 111
1

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);
});
A. Wolff
  • 74,033
  • 9
  • 94
  • 155
1

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);
        }
})
Karl-André Gagnon
  • 33,662
  • 5
  • 50
  • 75
0

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?

Community
  • 1
  • 1
Broxzier
  • 2,909
  • 17
  • 36