How to uncheck a radio button?
Asked Answered
G

17

549

I have group of radio buttons that I want to uncheck after an AJAX form is submitted using jQuery. I have the following function:

function clearForm(){
  $('#frm input[type="text"]').each(function(){
      $(this).val("");  
  });
  $('#frm input[type="radio":checked]').each(function(){
      $(this).checked = false;  
  });
 }

With the help of this function, I can clear the values at the text boxes, but I can't clear the values of the radio buttons.

By the way, I also tried $(this).val(""); but that didn't work.

Geomancy answered 22/1, 2010 at 13:42 Comment(2)
You wouldn't need the each function. You could just call the function you want upon the jQuery object. See my answer belowBernadinebernadotte
no need for each() function.. jQuery("input:radio").removeAttr("checked");Stephine
P
845

either (plain js)

this.checked = false;

or (jQuery)

$(this).prop('checked', false);
// Note that the pre-jQuery 1.6 idiom was
// $(this).attr('checked', false);

See jQuery prop() help page for an explanation on the difference between attr() and prop() and why prop() is now preferable.
prop() was introduced with jQuery 1.6 in May 2011.

Prehensile answered 22/1, 2010 at 13:47 Comment(7)
PPL, be aware that his behavior is changing on 1.6 in favor of prop(), while .attr() will be restricted to actual attributesCrayton
So is it best to use plain JS here?Exhilarative
@Pete: I would say that if you have a system built up on jQuery, then the additional advantage that gives you is that if there is ever a browser that handles this differently, you will be able to delegate the browser support to the library. However, if your software doesn't currently use jQuery, it wouldn't be worth the overhead to actually include the library just for this.Prehensile
@David Hedlund : I suppose you are implying that all major browsers handle this the same way as of today, right?Percy
The jQuery version doesn't work for me in Chrome with jQuery 1.9. It has no effect on the radio button. The plain JS version however does work.Factor
@qris: Your problem is probably somewhere else. Simple demo, using jQuery 1.9. Sure works in my Chrome.Prehensile
ASs of 2020, This is still working. your welcome XDBloodthirsty
B
98

You wouldn't need the each function

$("input:radio").attr("checked", false);

Or

$("input:radio").removeAttr("checked");

The same should also apply to your textbox:

$('#frm input[type="text"]').val("");

But you could improve this

$('#frm input:text').val("");
Bernadinebernadotte answered 22/1, 2010 at 13:49 Comment(5)
.removeAttr is likely to cause problems.Caddaric
Care to expand on how? Or provide a link?Bernadinebernadotte
Yes, Kzqai, I am also curious my answer was down-voted for this as well. The documentation mentions no risk.Anterior
Relevant documentation is actually on the .prop() method: api.jquery.com/prop Quote "Properties generally affect the dynamic state of a DOM element without changing the serialized HTML attribute. Examples include the value property of input elements, the disabled property of inputs and buttons, or the checked property of a checkbox. The .prop() method should be used to set disabled and checked instead of the .attr() method. The .val() method should be used for getting and setting value." This means that...Caddaric
...This means that .attr() will be altering a different underlying source than .prop(), the serialized html attribute instead of the DOM, and while this may be compatible now (e.g. jQuery 1.9 may modify both when when .attr() is used), that's no guarantee it will be upkept to modify both in the future when .prop() is canonical. For example, if you use .attr('checked', false); and a library you use includes .prop('checked', true);, there's going to be an inherent conflict that could cause annoying bugs.Caddaric
A
31

Try

$(this).removeAttr('checked')

Since a lot of browsers will interpret 'checked=anything' as true. This will remove the checked attribute altogether.

Hope this helps.

Anterior answered 22/1, 2010 at 13:49 Comment(2)
Also, as one of the other answers mentions, you wont need the each function; you could just chain the removeAttr call to the selector.Anterior
NOTE: this response is from 2010. At that time, this was a valid and accepted approach. Since then it has become deprecated.Anterior
S
21

Thanks Patrick, you made my day! It's mousedown you have to use. However I've improved the code so you can handle a group of radio buttons.

//We need to bind click handler as well
//as FF sets button checked after mousedown, but before click
$('input:radio').bind('click mousedown', (function() {
    //Capture radio button status within its handler scope,
    //so we do not use any global vars and every radio button keeps its own status.
    //This required to uncheck them later.
    //We need to store status separately as browser updates checked status before click handler called,
    //so radio button will always be checked.
    var isChecked;

    return function(event) {
        //console.log(event.type + ": " + this.checked);

        if(event.type == 'click') {
            //console.log(isChecked);

            if(isChecked) {
                //Uncheck and update status
                isChecked = this.checked = false;
            } else {
                //Update status
                //Browser will check the button by itself
                isChecked = true;

                //Do something else if radio button selected
                /*
                if(this.value == 'somevalue') {
                    doSomething();
                } else {
                    doSomethingElse();
                }
                */
            }
    } else {
        //Get the right status before browser sets it
        //We need to use onmousedown event here, as it is the only cross-browser compatible event for radio buttons
        isChecked = this.checked;
    }
}})());
Sedative answered 4/11, 2010 at 19:51 Comment(0)
A
21

Slight modification of Laurynas' plugin based on Igor's code. This accommodates possible labels associated with the radio buttons being targeted:

(function ($) {
    $.fn.uncheckableRadio = function () {

        return this.each(function () {
            var radio = this;
                $('label[for="' + radio.id + '"]').add(radio).mousedown(function () {
                    $(radio).data('wasChecked', radio.checked);
                });

                $('label[for="' + radio.id + '"]').add(radio).click(function () {
                    if ($(radio).data('wasChecked'))
                        radio.checked = false;
                });
           });
    };
})(jQuery);
Alienate answered 29/11, 2011 at 21:41 Comment(1)
It dependends on how the labels are used, if they use IDs then this code works, if the radio button is nested in the label it doesn't. You can use this even more enhanced version : gist.github.com/eikes/9484101Porterhouse
E
20

Rewrite of Igor's code as plugin.

Use:

$('input[type=radio]').uncheckableRadio();

Plugin:

(function( $ ){

    $.fn.uncheckableRadio = function() {

        return this.each(function() {
            $(this).mousedown(function() {
                $(this).data('wasChecked', this.checked);
            });

            $(this).click(function() {
                if ($(this).data('wasChecked'))
                    this.checked = false;
            });
        });

    };

})( jQuery );
Edgebone answered 18/9, 2011 at 13:56 Comment(3)
Unselecting doesn't work if I'm clicking on the label. So while it is possible to select a radio by clicking on the label, unselecting only works by clicking on the radio button itself.Conakry
@Alienate has a solution that seems to work with labels, too.Conakry
It dependends on how the labels are used, if they use IDs then @Alienate code works, if the radio button is nested in the label, use this version: gist.github.com/eikes/9484101Porterhouse
L
18

For radio and radio group:

$(document).ready(function() {
    $(document).find("input:checked[type='radio']").addClass('bounce');   
    $("input[type='radio']").click(function() {
        $(this).prop('checked', false);
        $(this).toggleClass('bounce');

        if( $(this).hasClass('bounce') ) {
            $(this).prop('checked', true);
            $(document).find("input:not(:checked)[type='radio']").removeClass('bounce');
        }
    });
});
Lyda answered 30/10, 2012 at 11:36 Comment(0)
W
14

Try this, this will do the trick:

        $(document).ready(function() {
           $("input[type='radio']").mousedown(function(e) {
                if ($(this).attr("checked") == true) {
                   setTimeout("$('input[id=" + $(this).attr('id') + "]').removeAttr('checked');", 200);}
                else {
                    return true
                }
            });
        });
Whipstitch answered 1/10, 2010 at 11:2 Comment(0)
N
12

Try

$(this).attr("checked" , false );
Ningsia answered 22/1, 2010 at 13:47 Comment(0)
C
12

You can also simulate the radiobutton behavior using only checkboxes:

<input type="checkbox" class="fakeRadio" checked />
<input type="checkbox" class="fakeRadio" />
<input type="checkbox" class="fakeRadio" />

Then, you can use this simple code to work for you:

$(".fakeRadio").click(function(){
    $(".fakeRadio").prop( "checked", false );
    $(this).prop( "checked", true );
});

It works fine and you have more control over the behavior of each button.

You can try it by yourself at: http://jsfiddle.net/almircampos/n1zvrs0c/

This fork also let's you unselect all as requested in a comment: http://jsfiddle.net/5ry8n4f4/

Chaste answered 18/8, 2014 at 7:3 Comment(1)
This is great, except you cannot uncheck all the boxes.Macguiness
A
10

You can use this JQuery for uncheck radiobutton

$('input:radio[name="IntroducerType"]').removeAttr('checked');
                $('input:radio[name="IntroducerType"]').prop('checked', false);
Amphitrite answered 16/10, 2018 at 6:50 Comment(2)
This is what I wanted! The code can be directly run in the DOM, i.e., Console, for changing the loaded HTML page. Thanks.Linotype
Perfect Answer!!! +1 even ChatGPT failed to answer this :DChappie
S
7

Use this

$("input[name='nameOfYourRadioButton']").attr("checked", false);
Stelu answered 9/1, 2017 at 19:59 Comment(0)
S
6

Just put the following code for jQuery :

jQuery("input:radio").removeAttr("checked");

And for javascript :

$("input:radio").removeAttr("checked");

There is no need to put any foreach loop , .each() fubction or any thing

Stephine answered 9/4, 2015 at 7:4 Comment(1)
You realise that `$("input:radio").removeAttr("checked"); isn’t plain JavaScript, don’t you?Impiety
A
5
$('#frm input[type="radio":checked]').each(function(){
   $(this).checked = false;  
  });

This is almost good but you missed the [0]

Correct ->> $(this)[0].checked = false;

Apologetics answered 20/12, 2013 at 18:16 Comment(1)
or simply: this.checked = false;Porterhouse
O
1
function setRadio(obj) 
{
    if($("input[name='r_"+obj.value+"']").val() == 0 ){
      obj.checked = true
     $("input[name='r_"+obj.value+"']").val(1);
    }else{
      obj.checked = false;
      $("input[name='r_"+obj.value+"']").val(0);
    }

}

<input type="radio" id="planoT" name="planoT[{ID_PLANO}]" value="{ID_PLANO}" onclick="setRadio(this)" > <input type="hidden" id="r_{ID_PLANO}" name="r_{ID_PLANO}" value="0" >

:D

Ostosis answered 16/6, 2014 at 14:43 Comment(0)
N
0

A full example using bootstrap, jQuery.

I added a class checked on load of the page, after each click I toggled the checked-class. After that I rechecked all states of the buttons and set the checked-class accordingly (if another input was checked).

$(() => {
  // Add class 'checked' to checked radio buttons on load
  addCheckedToCheckedRadio();

  // Bind click event to allow deselecting radio buttons
  $('input[type="radio"].allow-deselect').click(function(event) {
    if ($(this).hasClass('checked')) {
      this.checked = false;
    }
    addCheckedToCheckedRadio();
  });
});

function addCheckedToCheckedRadio() {
  $('input[type="radio"].allow-deselect').each(function() {
    $(this).toggleClass('checked', this.checked);
  });
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-kenU1KFdBIe4zVF0s0G1M5b4hcpxyD9F7jL+jjXkk+Q2h455rYXK/7HAuoJl+0I4" crossorigin="anonymous"></script>


<div class="container mt-3">
  <div class="card">
    <div class="card-body">
      <h5 class="card-title">Gender</h5>
      <div class="form-check">
        <input type="radio" name="gender" value="male" id="gender_male" class="form-check-input allow-deselect">
        <label for="gender_male" class="form-check-label">Male</label>
      </div>
      <div class="form-check">
        <input type="radio" name="gender" value="female" id="gender_female" class="form-check-input allow-deselect checked">
        <label for="gender_female" class="form-check-label">Female</label>
      </div>
      <div class="form-check">
        <input type="radio" name="gender" value="other" id="gender_other" class="form-check-input allow-deselect">
        <label for="gender_other" class="form-check-label">Other</label>
      </div>
    </div>
  </div>
</div>
Nunley answered 13/2 at 14:21 Comment(0)
L
-2
$('input[id^="rad"]').dblclick(function(){
    var nombre = $(this).attr('id');
    var checked =  $(this).is(":checked") ;
    if(checked){
        $("input[id="+nombre+"]:radio").prop( "checked", false );
    }
});

Every time you have a double click in a checked radio the checked changes to false

My radios begin with id=radxxxxxxxx because I use this id selector.

Lovettalovich answered 13/8, 2014 at 16:11 Comment(4)
Please write the answer in (understandable) english.Ogilvie
@Ogilvie what if someone doesn't know English?Coel
@AlphaMale english is the official language on this site.Partain
@Partain Not all programmers come from "English" speaking countries. Does that mean they can't post on this forum? Secondly, it's Been 2 years mate. Thanks for enlightening me tho.Coel

© 2022 - 2024 — McMap. All rights reserved.