Jason
Jason

Reputation: 4967

Add CSS to a checked radio button and label in jQuery

I am using images as radio buttons and want to add a CSS style to the radio button (image) that is checked through jQuery.

This is the HTMl code which has the radio buttons and labels:

<input class="radio" type="radio" name="asw_options[box_background_color]" id="box_background_color0" value="aqua_solid"  checked='checked'>
<label for="box_background_color0"><img src="images/backgrounds/aqua.png"></label>
<input class="radio" type="radio" name="asw_options[box_background_color]" id="box_background_color1" value="blue_solid" >
<label for="box_background_color1"><img src="images/backgrounds/blue.png"></label>
<input class="radio" type="radio" name="asw_options[box_background_color]" id="box_background_color2" value="black_solid" >
<label for="box_background_color2"><img src="images/backgrounds/black.png"></label>

This is the jquery code I use to make the radio buttons work as images:

$('#solidcolor input:radio').addClass('input_hidden');
$('#solidcolor label').click(function() {
    $(this).addClass('selected').siblings().removeClass('selected');
});

This works great. You select an image and it checks the hidden radio button and highlights the images so that you know that you made a selection. I then save the settings, which works fine.

What I want to do know, is when the page reloads I want to add a solid 3px black border to the checked radio button (image label) so that you know which choice you previously made.

What currently happens is when you reload the page all the images (labels) end up with a black border.

This is the jQuery I am trying to use to highlight the previously saved radio button.

$("#solidcolor input[type='radio']:checked").each( 
function() { 
   $('#solidcolor label').css("border", "solid 3px black");
} 
);

Can this be done through jQuery or would I be better off to try and highlight the previously selected radio button through CSS?

I have also experimented with different jQuery functions and if I use this code it alerts me to the previously correct checked radio button, however with this code I do not know how to use it to make it add the CSS border to that certain label or checked radio button.

var isChecked = $("#solidcolor input[name=asw_options[box_background_color]]:checked").val();
 alert(isChecked);

Please help, I have been banging my head on tis one for three days now.

Thank You

EDIT:

I have just set up a jsfiddle to show what I mean

jSFiddle Example

Upvotes: 1

Views: 7313

Answers (1)

Tim Banks
Tim Banks

Reputation: 7189

One thing you might try is updating the .each callback. I added an attribute selector to the label selector in order to get the label associated with the checked checkbox

$("#solidcolor input[type='radio']:checked").each( 
    function() { 
       $("#solidcolor label[for='" + this.id + "']").css("border", "solid 3px black");
    } 
);

Upvotes: 4

Related Questions