3

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

3 Answers 3

9
$("#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');
    } 
});

or

$("#new").click(function() {
    $(this).closest('p').toggleClass('white',this.checked);
});

you should have a css definition like this

.white {
   color: white;
}
Sign up to request clarification or add additional context in comments.

1 Comment

This worked for me too I had to adapt it slightly to suit my needs, but it solved a problem I didn't even know I had.
1
$("#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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.