views:

47

answers:

3

So i have a form. Most of the questions asked in the forms are using Radio inputs.

i'm going with

<label>Option1
    <input type="radio">
</label>
<label>Option2
    <input type="radio">
</label>

I'm styling the Labels using :hover, giving it a subtle background change to indicate which option you are highlighting. However, i want the label for the selected option to have a different colored background. Is there any way of doing this using CSS, or do I have to go with jQuery? What i want to do is declare a style for the parent (label) of the checked input box.

Upon further brainstorming i'd like to change the parent fieldset's bkg-color upon having all required fields filled in. I'm starting to feel jQuery is the way to go here..?

[Notes:] Using HTML5 / CSS3 / jQuery. Only has to be compatible with Chrome or Firefox. This is something that is to run locally on a laptop, so as long as it runs fine on that computer I don't have to worry about compatibility on older browsers etc. :)

Edit: Solution posted by Nick Carver. A few additions to get this to work properly with radio buttons. Posting for completeness:

$('input[type="radio"]').change(function() {
    var tmp=$(this).attr('name');
    $('input[name="'+tmp+'"]').parent("label").removeClass("checked");
    $(this).parent("label").toggleClass("checked", this.selected);      
});

$('input[type="checkbox"]').change(function() {
    $(this).parent("label").toggleClass("checked", this.selected);
});
A: 

Can't do it with vanilla CSS. You'd need to use jQuery to add some onclick behavior to the radio boxes that add/remove a class from the label for selected. Then you could add the :hover class to your selector. For best results I think that you'll need to make sure your labels are set to display:inline-block; for best results.

pinkfloydx33
+1  A: 

There isn't a way with pure CSS, since you're styling a parent and not a child. If you did it in jQuery you'd do something like:

$("fieldset :radio").change(function() {
  $(this).closest("label").toggleClass("onClass", this.checked);
});

The overall <fieldset> styling would depend on your markup, if you have some sort of container each radio set is in you could check if none of those had a :checked element within...if they all do, then use the same .toggleClass() approach to set that "all checked" class on or off.

Nick Craver
Awesome, thanks a lot :)
Fade
@Fade - welcome!
Nick Craver
This worked perfectly on checkboxes, but didn't quite work as expected on radio groups. I had to make an extra function targetting radio groups. Code follows:
Fade
@Fade - Can you post the markup that includes the whole container? As in, are all these labels in a `<div>` or something, each group?
Nick Craver
http://dev.ute.no/TU-bruker/form.html (don't mind the layout / color choice. Need to get the cogs working before i continue :))
Fade