To style the labels of unchecked radio buttons when there is only one checked radio button, you’ll need to use a combination of CSS and JavaScript (or jQuery). Here’s a step-by-step approach to achieve this:
HTML Structure
Make sure your HTML structure is something like this:
<div>
<input type="radio" id="radio1" name="group" value="1">
<label for="radio1">Option 1</label>
</div>
<div>
<input type="radio" id="radio2" name="group" value="2">
<label for="radio2">Option 2</label>
</div>
<div>
<input type="radio" id="radio3" name="group" value="3">
<label for="radio3">Option 3</label>
</div>
CSS
Define styles for unchecked labels:
/* Default styling for all labels */
label {
color: black; /* default color */
}
/* Styling for unchecked labels when only one radio is checked */
label.unchecked {
color: gray; /* or any style you prefer */
}
JavaScript
Use JavaScript to apply the unchecked
class to labels when there is only one checked radio button:
document.addEventListener('DOMContentLoaded', function() {
const radioButtons = document.querySelectorAll('input[type="radio"]');
function updateLabels() {
const checkedRadios = document.querySelectorAll('input[type="radio"]:checked');
// If there is exactly one radio button checked
if (checkedRadios.length === 1) {
// Get the checked radio button's ID
const checkedId = checkedRadios[0].id;
// Remove 'unchecked' class from all labels
document.querySelectorAll('label').forEach(label => {
label.classList.remove('unchecked');
});
// Add 'unchecked' class to labels of unchecked radio buttons
radioButtons.forEach(radio => {
if (radio.checked) return; // Skip checked radio
const label = document.querySelector(`label[for="${radio.id}"]`);
if (label) {
label.classList.add('unchecked');
}
});
} else {
// If not exactly one radio button is checked, remove 'unchecked' class from all labels
document.querySelectorAll('label').forEach(label => {
label.classList.remove('unchecked');
});
}
}
// Attach event listeners to all radio buttons
radioButtons.forEach(radio => {
radio.addEventListener('change', updateLabels);
});
// Initial update
updateLabels();
});
Explanation
- HTML: Radio buttons are grouped using the
name
attribute, which ensures only one can be selected at a time. - CSS: Default label styles are defined, with a specific style for unchecked labels.
- JavaScript:
- Listens for changes to the radio buttons.
- Checks if exactly one radio button is selected.
- Applies the
unchecked
class to the labels of unchecked radio buttons.
Leave a Reply