noneJavaScript
noneJavaScript

Reputation: 845

Change style if checkbox checked

How can I do that ? This is not working, no results, no effect, no error output.

$('input[type=checkbox]').each(function() 
    {
            if($(this).attr("checked") === true){
            $('.hoverbox .a').css('text-transform', 'uppercase');
            }
            else
            {
            $('.hoverbox .a').css('text-transform', 'lowercase');
            }
    });

Upvotes: 0

Views: 5961

Answers (2)

Blazemonger
Blazemonger

Reputation: 93003

You probably need an event handler:

$('input[type=checkbox]').on('change',function(e) {
   // do stuff
});

http://api.jquery.com/on

Or possibly (it's hard for me to understand your intentions) you need to use .prop() instead of .attr():

if ($(this).prop('checked')) {
    // do something 
} else {
    // do something else
}

update: Putting it all together:

$('input[type=checkbox]').on('change',function(e) {
    if ($(this).prop('checked')) {
        $('.hoverbox .a').css('text-transform', 'uppercase');
    } else {
        $('.hoverbox .a').css('text-transform', 'lowercase');
    };
});

Although adding a custom class and toggling it would save you a little trouble:

$('input[type=checkbox]').on('change',function(e) {
    $('.hoverbox .a').toggleClass('uppercase');
});

CSS:

.hoverbox .a {
    text-transform: lowercase;
}
.hoverbox .a.uppercase {
    text-transform: uppercase;
}

Upvotes: 4

PlantTheIdea
PlantTheIdea

Reputation: 16369

Why cant you use CSS? Why waste javascript?

input[type=checkbox]:checked + div {
    text-decoration:underline;
}

Upvotes: 2

Related Questions