Satch3000
Satch3000

Reputation: 49422

JQuery toggleClass with 2 Classes?

I am working with this code: (Updated)

   <script>
$(function(){
//Radio Item 1
$("#radio1").change(function() {

$("#defaultwrapper").addClass("background_color_selected");
$("#default_wrapper").removeClass("def_background_color");

});

//Radio Item 2
$("#radio2").change(function() {

$("#default_wrapper2").addClass("background_color_selected");
$("#default_wrapper2").removeClass("def_background_color");

});



});
</script>

My problem is that I need the background-color of the selected radio to change and it's not toggling right now

Upvotes: 0

Views: 504

Answers (4)

Krzysztof
Krzysztof

Reputation: 16150

(Update) In jQuery no event is fired when radio is unselected. Try to create global handler:

$(function(){
    $("input[type=radio]").change(function() {
        $("input[type='radio']", $(this).parent().parent()).each(function() {
            $(this).parent()
                .toggleClass("background_color_selected", this.checked)
                .toggleClass("def_background_color", !this.checked);
        });
    });
});

For html:

<div>
    <div class="def_background_color"><input type="radio" id="radio1" name="aaa" /> One</div>
    <div class="def_background_color"><input type="radio" id="radio2" name="aaa" /> Two</div>
</div>

Working sample: http://jsfiddle.net/THrYJ/

Upvotes: 1

Andreas Eriksson
Andreas Eriksson

Reputation: 9027

  $(function(){
        $("#myradio").change(function() {
    $("#wrapper").toggleClass("classOne", this.checked).toggleClass("classTwo", !this.checked)
        }).change();
    })

Upvotes: 2

Murtaza
Murtaza

Reputation: 3065

Hi i had the same problem but this is what i have done in my project...

    <script>
    $(".rtPanhold01").addClass("rtPanhold02");
        $(".rtPanhold01").removeClass("rtPanhold01");
</script>

Upvotes: 1

Snicksie
Snicksie

Reputation: 1997

If you have classOne present at first (f.e. <div class="classOne" id="test">Text</div>) you can switch classes like this: $("#test").toggleClass("classOne classTwo");. This will remove the class classOne (because its present yet) and it will add the class classTwo (as its not present yet).

Upvotes: 1

Related Questions