Skip to content

Instantly share code, notes, and snippets.

@karmiphuc
Created January 13, 2014 12:00
Show Gist options
  • Save karmiphuc/8399124 to your computer and use it in GitHub Desktop.
Save karmiphuc/8399124 to your computer and use it in GitHub Desktop.
Special approach, to reset the radio button that has been checked, in case there's no default checked buttons. Cannot use normal approach "$(object).removeAttr('checked')"
<!-- There is no default checked button -->
<input type="radio" name="my-radio" value="0">Choice 1</input>
<input type="radio" name="my-radio" value="1">Choice 2</input>
<input type="radio" name="my-radio" value="2">Choice 3</input>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
// Global index
var rdoActiveIndex = -1;
$('input[name=my-radio]').on('click', function(e) {
var oldActiveIndex = rdoActiveIndex;
rdoActiveIndex = $(this).val();
// Reset checking status
$('input[name=my-radio]').removeAttr('checked');
if (oldActiveIndex != rdoActiveIndex) {
$('input[name=my-radio][value='+rdoActiveIndex+']').attr('checked','checked');
} else {
// reset index
rdoActiveIndex = -1;
}
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment