Reputation: 3698
I'm trying to change background-color of a label when input[type='radio'] is checked. This is my HTML:
<div class="type">
<ul id="id_type">
<li><label for="id_type_0"><input type="radio" name="type" value="inc" required="" id="id_type_0" checked="">
Income</label>
</li>
<li><label for="id_type_1"><input type="radio" name="type" value="exp" required="" id="id_type_1">
Expense</label>
</li>
</ul>
</div>
...as you can see, the label wraps the radio input.
This is the selector I'm using:
.type input[type=radio]:checked ~ label {
background-color:#e0e0e0;
}
however having no success.
How can I overcome the issue?
I can't alter the HTML, it's generated by Django.
Upvotes: 0
Views: 135
Reputation: 639
Because of your radio input inside of label. Check this;
var inputs = document.querySelectorAll("input[type=radio]");
Array.from(inputs).forEach(function(elem){
elem.addEventListener('change',function(a){
Array.from(inputs).forEach(function(z){
if(z.parentNode.classList.contains("yourClass")){
z.parentNode.classList.remove("yourClass")
}
});
a.target.parentNode.classList.add("yourClass");
})
});
.yourClass{
background-color: #e0e0e0;
}
<div class="type">
<ul id="id_type">
<li><label for="id_type_0"><input type="radio" name="type" value="inc" required="" id="id_type_0" checked="">
Income</label>
</li>
<li><label for="id_type_1"><input type="radio" name="type" value="exp" required="" id="id_type_1">
Expense</label>
</li>
</ul>
</div>
Upvotes: 0
Reputation: 454
.type input[type=radio]:checked+label {
background-color: #e0e0e0;;
}
<div class="type">
<ul id="id_type">
<li>
<input type="radio" name="type" value="inc" required="" id="id_type_0" checked="">
<label for="id_type_0">Income</label>
</li>
<li>
<input type="radio" name="type" value="exp" required="" id="id_type_1">
<label for="id_type_1">Expense</label>
</li>
</ul>
</div>
Upvotes: 2