1

I have a radio button and I need to add a style to its parent div when the radio button is checked. This I need to do only with css. In the below html, if the radio is checked, i need to apply a color to the div "options"

HTML

<div class="options"> 
<span class="option_radio">
        <input type="radio" name="payMethod" id="payMethod1" value="aaa" >
</span>
<span class="option_image">
    <label for="payMethod1">
        <img src="abc.png" >
    </label>
</span>
</div>

I tried the below approaches but its not coming correctly

.options input[type="radio"]:checked span{
background-color:black;
}

.options input[type="radio"]:checked div.options{
background-color:black;
}

could somebody please help me on this

user1049057
  • 459
  • 4
  • 15
  • 36
  • That won't work as you try to, since this would mean you alter the rules for a `span` or `div` that is located _inside_ a radio button... – arkascha Apr 23 '14 at 13:09
  • You can't target parents in css http://stackoverflow.com/questions/1014861/is-there-a-css-parent-selector – Seth Apr 23 '14 at 13:10

4 Answers4

0

Sorry, can't do that yet. You can only go down the tree, not up it. You will either need to make the elements you want to style siblings or descendents of the radio button. Ancestor selectors do not yet exist:

http://css-tricks.com/parent-selectors-in-css/

Mister Epic
  • 16,295
  • 13
  • 76
  • 147
0
<input type="radio" name="payMethod" id="payMethod1" value="aaa" />

<div class="options"> 
<span class="option_radio">
</span>
<span class="option_image">
    <label for="payMethod1">
        <img src="abc.png" />
    </label>
</span>
</div>

css

input[type='radio']:checked + div.options {
  background-color:green;
}
input[type='radio']:checked + div.options span {
  background-color:red;
}  
alessandrio
  • 4,282
  • 2
  • 29
  • 40
0

That would require using parent selectors from CSS4 http://www.w3.org/TR/selectors4/ Unfortunately CSS4 is not yet available. So for today it is not possible to do that using pure css.

Tirlipirli
  • 103
  • 2
  • 10
0

Javascript is your answer. Provided Vanilla and jQuery examples.

var payMethod = document.querySelector('#payMethod1');

payMethod.onchange = function() {
    alert('clicked')
    // Get span and div
    if(this.checked) {
        var elements = document.querySelectorAll('.option_radio, .options');

        // Loop elements & add class
        for(var i = 0; i < elements.length; i++) {
            if (elements[i].classList)
              elements[i].classList.add("checked");
            else
              elements[i].className += ' checked';
        }
    }
};

//jQuery implementation
$('#payMethod1').change(function() {
   if($(this).is(':checked')) {
       $('.option_radio, .options').addClass('checked');
   }
});
Seth
  • 10,198
  • 10
  • 45
  • 68