Visually highlight selected radios and checkboxes
I notice that most touch enabled devices (and more recent desktop browsers) do a nice thing with the checkbox and radio form elements — when marked up with a wrapping label, the whole label becomes tappable/clickable, making it much easier to select items in a list of checkboxes or radio buttons.
That's nice, but what I didn't like was the default -webkit
styes for :checked
checkboxes and radio elements — way too subtle in my opinion. I was also frustrated with the lack of style options available to these elements through CSS.
Instead, I decided to style the labels themselves, making it more apparent which ones have been selected. This has a bonus of being a nice visual for desktop users as well.
The 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');
});
Bonus
Here is a link to a JSFiddle with basic styling in place. Play with it to see the effect, and use it however you wish.