Kaherdin
Kaherdin

Reputation: 2127

if :checked add class to this

I have a small problem. I want to check if a checkbox is checked and if it is checked, I want to add a class to his first brother. HTML :

    <input class="box" type="checkbox">
    <p class="red">Red text </p>

    <input class="box" checked type="checkbox">
    <p class="red">I want this text in blue </p>

JS :

    if(jQuery(".box").is(":checked")) {
    jQuery(this).next().attr('class', 'blue');                              
}

Example here : http://jsfiddle.net/LVEqn/

Thanks in advance !

Upvotes: 3

Views: 3960

Answers (3)

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382102

If you want to add the class 'blue' to all elements following a checked box, do this :

$(".box:checked").next().addClass('blue');

If you want to replace the existing class, do

$(".box:checked").next().attr('class', 'blue');

If you want this to be dynamic, that is change when the user checks or unchecks, do

$(".box").change(function(){
    $(this).next().attr('class', $(this).is(':checked') ? 'blue' : 'red');
});

DEMONSTRATION

Upvotes: 6

Bram Vanroy
Bram Vanroy

Reputation: 28437

jQuery

$(".box:checked").next().addClass("blue");

CSS

.blue {color: blue !important;}

Upvotes: 1

mgraph
mgraph

Reputation: 15338

try this:

jQuery(".box:checked").each(function(){
    jQuery(this).next().attr('class', 'blue');
})  

demo: http://jsfiddle.net/LVEqn/2/

Upvotes: 2

Related Questions