2

I want to create a radio button that can have an unchecked value. So I created the code:

$('form').on('click', 'input[type="radio"]:checked', function (event) {
    $(this).prop("checked", false);
});

Well, this is pretty straightforward: click on a checked radio, uncheck it.

But, what happens is that it never checks the radio in the first place. When I click an unchecked radio it checks before detecting if is checked, then considers it checked and unchecks it.

Well, this is not a duplicate as it asks a different question. It's not about how to uncheck, but how to automatically uncheck upon clicking.

How can I go around this problem?

Ibrahim Khan
  • 20,616
  • 7
  • 42
  • 55
sigmaxf
  • 7,998
  • 15
  • 65
  • 125

2 Answers2

0

You can solve your issue like following.

$('form :radio').attr('data-ischecked', function() {
    return this.checked;
}); //set initial status in data-ischecked attribute 

$('form').on('click', ':radio', function () {
    var status = $(this).data('ischecked'); //get status
    status && $(this).prop("checked", false); //uncheck if checked
    $(this).data('ischecked', !status); //toggle status
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
    <input type="radio"/>
    <input type="radio"/>
</form>
Ibrahim Khan
  • 20,616
  • 7
  • 42
  • 55
-1

Your example only executes when the button is clicked. To have the radio button be checked when the page loads, I would put a $(document).onload() event that sets the button's value to checked.

scott
  • 101
  • 3