Skip to content

Instantly share code, notes, and snippets.

@harvzor
Created August 20, 2014 11:37
Show Gist options
  • Save harvzor/8bc36e3bcfbb7aa106e0 to your computer and use it in GitHub Desktop.
Save harvzor/8bc36e3bcfbb7aa106e0 to your computer and use it in GitHub Desktop.
JS Radio Selector
<label class="radio" for="nice_day_yes">Yes</label>
<input id="nice_day_yes" type="radio" name="nide_day" value="yes"/>
<span>/</span>
<label class="radio" for="nice_day_no">No</label>
<input id="nice_day_no" type="radio" name="nice_day" value="no"/>
// On load, show that a radio has been checked
$('input[type="radio"]').each(function() {
if($(this).is(':checked')) {
var id = $(this).attr('id');
var name = $(this).attr('name');
}
// Find all inputs with same name
$('input[name="' + name + '"]').each(function() {
// Check if it is actually the same as the one clicked on
// (if it is, do nothing)
// (if it isn't, then add a strike class)
if($(this).prev().attr('for') !== id) {
$(this).prev().addClass('strike');
}
});
});
// If a radio field has been selected, then the other radio
// will be crossed out
$('input[type="radio"]').change(function() {
var id = $(this).attr('id');
var name = $(this).attr('name');
// Remove all strike classes
$(this).prev().removeClass('strike');
// Find all inputs with the name which is the same as the one clicked on
$('input[name="' + name + '"]').each(function() {
// Check if it is actually the same as the one clicked on
// (if it is, do nothing)
// (if it isn't, then add a strike class)
if($(this).prev().attr('for') !== id) {
$(this).prev().addClass('strike');
}
});
});
input[type="radio"] {
display:none;
}
label.radio {
display:inline-block;
margin:0;
cursor:pointer;
}
label.radio.strike {
text-decoration:line-through;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment