Benjamin
Benjamin

Reputation: 121

JQuery: Change class when radiobutton is clicked

I need some help with javascript.

Here is the link to the code in JSFIDDLE: http://jsfiddle.net/Gopher69/B98kZ/4/

My JS is:

$(document).ready(function() {
//add the Selected class to the checked radio button
$('[type=radio]').parent().addClass("selected");
//If another radio button is clicked, add the select class, and remove it from the       previously selected radio
$('input').click(function() {
    $('input:not(:checked)').parent().removeClass("radio  validate-one-required-by-name product-custom-option").find("class").html("radio  validate-one-required-by-name product-custom-option");
    $('input:checked').parent().addClass("radio  validate-one-required-by-name product-custom-option").find("class").html("radio  validate-one-required-by-name product-custom-option active");
});});

I want to adjust the the background color for the radio buttons just like I did with the hover effect with css. So I need to add something like "checked" to the class when the radiobutton is active.

I found this post but I'm juts not getting foreword: jQuery Checkbox selection and change class

If somebody could help me out, I would be very thankfull.

Upvotes: 1

Views: 4092

Answers (3)

Robin van Baalen
Robin van Baalen

Reputation: 3651

Based on @Krunal Goswami's answer - even shorter:

$("#" + elementId).on("change",function(){
    $(this).toggleClass("checked");
});

Note

That should do your trick. Although I don't recommend using this. Instead try a 'custom checkbox' implementation / jQuery plugin since native browser checkboxes don't really like being styled (cross browser).

Upvotes: 0

Krunal Goswami
Krunal Goswami

Reputation: 65

$("#" + radioelementid).on("change",function(){  
$(this).addClass("testClass")   
//or   
$(this).removeClass("testClass");
});

Upvotes: 0

gamehelp16
gamehelp16

Reputation: 1101

you can use pure css to do this:

  input[type="radio"]:checked {
    /* put some style here */
  }

Upvotes: 3

Related Questions