Reputation: 1686
I have a basic button group like so:
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-b5kHyXgcpbZJO/tY9Ul7kGkf1S0CWuKcCD38l8YkeH8z8QjE0GmW1gYU5S9FOnJ0" crossorigin="anonymous"></script>
<div class="btn-group btn-group-toggle" data-toggle="buttons">
<label class="btn btn-secondary">
<input type="radio" id="1" name="responses" value="1">
Poor
</label>
<label class="btn btn-secondary">
<input type="radio" id="2" name="responses" value="2">
Average
</label>
<label class="btn btn-secondary">
<input type="radio" id="3" name="responses" value="3">
Good
</label>
<label class="btn btn-secondary">
<input type="radio" id="4" name="responses" value="4">
Very good
</label>
<label class="btn btn-secondary">
<input type="radio" id="5" name="responses" value="5">
Excellent
</label>
</div>
And I want to be able to change the background color of the checked option.
I cannot figure out how to select this in CSS. I am aiming for either a JS or CSS solution.
Upvotes: 0
Views: 39
Reputation: 3856
the idea is to capture the input
event on input
element and apply a styling class to it's parent label
, like so:
document.querySelectorAll('input').forEach(i => {
i.addEventListener('input', e => {
document.querySelectorAll('label').forEach(l => {
l.classList.remove('checked');
});
e.target.parentNode.classList.add('checked');
});
});
label.checked {
background-color: red !important;
}
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-b5kHyXgcpbZJO/tY9Ul7kGkf1S0CWuKcCD38l8YkeH8z8QjE0GmW1gYU5S9FOnJ0" crossorigin="anonymous"></script>
<div class="btn-group btn-group-toggle" data-toggle="buttons">
<label class="btn btn-secondary">
<input type="radio" id="1" name="responses" value="1">
Poor
</label>
<label class="btn btn-secondary">
<input type="radio" id="2" name="responses" value="2">
Average
</label>
<label class="btn btn-secondary">
<input type="radio" id="3" name="responses" value="3">
Good
</label>
<label class="btn btn-secondary">
<input type="radio" id="4" name="responses" value="4">
Very good
</label>
<label class="btn btn-secondary">
<input type="radio" id="5" name="responses" value="5">
Excellent
</label>
</div>
Upvotes: 1