tags:

views:

52

answers:

5

Hello,

I am very new on jquery, today i tried this following code

$("#new").click(function() {
    $('#new:checked').closest('p').css('color', 'white'); 
});

this works fine, when i clicked the checkbox, however when i untick the checkbox, it doesn't change back to original color back..

how do i achieve previous state of css after i untick?

thank you

A: 

RTFM

Dänu
+4  A: 
$("#new").click(function() {
    $(this).closest('p').css('color', this.checked?'white':'blue'); // just change the blue for your preference....
});

but I suggest you use class..

$("#new").click(function() {
    if (this.checked){
       $(this).closest('p').addClass('white');
    } else {
       $(this).closest('p').removeClass('white');
    } 
});

you should have a css definition like this

.white {
   color: white;
}
Reigel
bravo, worked. thanks
damien
A: 

You can always access the dom element of invocation calling this in an event handler:

$("#new").click(function() {
   var $this = $(this),
       $elem = $this.closest('p');

   if($this.is(':checked'){
      $elem.css('color', 'white');
   }
   else{
      $elem.css('color', 'black');
   }        
});

As you will notice, caching DOM elements is very common and a very good technique.

jAndy
+1  A: 
$("#new").toggle(function() {
   $('#new:checked').closest('p').css('color', 'white');
}, function() {
   $('#new:checked').closest('p').css('color', 'black');
});

You can do as u want to change. Even you can check whether the check box is checked or not. Otherwise if you know the loading state of the checkbox and if its always same, then no checking for 'checked' is required.

Sadat
A: 

Not adding anything new, just including a more succinct way to the same result:

$("#new").click(function() {
    var color = "black";
    if($(this).is(':checked')) color = "white";
    $(this).closest('p').css('color', color);
});
Ioannis Karadimas