0

$(".label").click(function(){
    var id = $("#uncheck");
    var value = id.val();
    if(value == 'unchecked'){
      id.val('checked');
    } else {
      id.val('unchecked');
      id.prop('checked', false);
    }
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label class='label' for='uncheck'>uncheck</label>
<input class='input' type='radio' id='uncheck' value='unchecked'>

I keep trying to uncheck the radio button but it won't work,

AXAI
  • 706
  • 6
  • 17
  • See here: https://stackoverflow.com/questions/5665915/how-to-check-a-radio-button-with-jquery – kangaro0 Sep 10 '17 at 16:43
  • Possible duplicate of https://stackoverflow.com/questions/5665915/how-to-check-a-radio-button-with-jquery – Ahmed Can Unbay Sep 10 '17 at 16:44
  • @turmuka isn't in my code `id.prop('checked', false);` is same as `$('#uncheck').prop("checked", flase)`? – AXAI Sep 10 '17 at 16:46
  • Having a label event handler do the opposite of what it would normally do is semantically incorrect. You might want to reconsider, since most people expect clicking text adjacent to a form element to toggle or focus its state. What you're doing here will just confuse a lot of users. – Patrick Roberts Sep 10 '17 at 16:56
  • What Patrick said, plus you may want to use a checkbox to signify on/off. Radios are normally for choosing "one out of many". – deg Sep 10 '17 at 16:59
  • https://stackoverflow.com/questions/6191621/jquery-check-uncheck-radio-button-onclick – Ahmed Can Unbay Sep 10 '17 at 17:11

1 Answers1

0

You should prevent the default action (label is setting the radio back). You can do it by returning false from your event handler:

$(".label").click(function(){
    var id = $("#uncheck");
    if(!!id.prop('checked')) {
      id.prop('checked', false);
      return false;
    }
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label class='label' for='uncheck'>uncheck</label>
<input class='input' type='radio' id='uncheck' value='unchecked'>

Or using event.preventDefault() method:

$(".label").click(function(e){
    var id = $("#uncheck");
    var value = id.val();
    if(value == 'unchecked'){
      id.val('checked');
    } else {
      e.preventDefault();
      id.val('unchecked');
      id.prop('checked', false);
    }  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label class='label' for='uncheck'>uncheck</label>
<input class='input' type='radio' id='uncheck' value='unchecked'>
Stanislav Kvitash
  • 4,614
  • 18
  • 29