Highlight selected radio/checkbox options
HTML
<form>
<fieldset title="Select some form elements">
<legend>Checkboxes</legend>
<label for="checkbox1">
<input id="checkbox1" name="checkbox" type="checkbox" checked="checked" />Choice A</label>
<label for="checkbox2">
<input id="checkbox2" name="checkbox" type="checkbox" />Choice B</label>
<label for="checkbox3">
<input id="checkbox3" name="checkbox" type="checkbox" />Choice C</label>
<legend>Radios</legend>
<label for="radio1">
<input id="radio1" name="checkbox" type="radio" checked="checked" />Choice A</label>
<label for="radio2">
<input id="radio2" name="checkbox" type="radio" />Choice B</label>
<label for="radio3">
<input id="radio3" name="checkbox" type="radio" />Choice C</label>
</fieldset>
</form>
CSS
form {
font-size: 1.25em;
line-height: 2;
font-family: sans-serif;
font-weight: normal;
color: #666;
}
label {
display: inline-block;
margin: 0 .25em;
padding: .125em .5em;
background-color: transparent;
}
input {
margin-right: .25em;
}
.active {
font-weight: bold;
color: #333;
background-color: #ffc;
}
JavaScript
/*
* Add a class to the selected radio/checkbox parent label
* Requires inputs to be nested in labels:
* <label for="checkbox2"><input id="checkbox2" name="checkbox" type="checkbox">Choice B</label>
* <label for="radio1"><input id="radio1" name="radio" type="radio" checked="checked">Option 1</label>
*/
$('input:radio').click(function () {
$('label:has(input:radio:checked)').addClass('active');
$('label:has(input:radio:not(:checked))').removeClass('active');
});
$('input:checkbox').click(function () {
$('label:has(input:checkbox:checked)').addClass('active');
$('label:has(input:checkbox:not(:checked))').removeClass('active');
});
/* Loop through them on initial page load as well */
$('input:radio').each(function () {
$('label:has(input:radio:checked)').addClass('active');
});
$('input:checkbox').each(function () {
$('label:has(input:checkbox:checked)').addClass('active');
});