Deselectable radio buttons

Clicking on a checked radio button would make it unchecked

by Muhammad Ikhsan

HTML

<div class="radio">
  <input type="radio" name="opt" class="deselectable-radio">Option 1
</div>
<div class="radio">
  <input type="radio" name="opt" class="deselectable-radio">Option 2
</div>

JavaScript

$(document).ready(function() {
  $.each($('.deselectable-radio'), function(k, v) {
    $(v).data('prevChecked', $(v).prop('checked').toString());
  });
});

$('.deselectable-radio').click(function(){
  console.log('propChecked: ' + $(this).prop('checked'));
  console.log('prevChecked: ' + $(this).data('prevChecked'));
  if ($(this).data('prevChecked') == 'true') {
    $(this).prop('checked', false)
      .data('prevChecked', 'false');
  } else {
    $(this).data('prevChecked', 'true');
  }
  console.log('so, I need to make it checked? ', $(this).prop('checked'));
});