544

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.

Gregg Bursey
  • 1,097
  • 2
  • 11
  • 16
systemsfault
  • 15,207
  • 12
  • 59
  • 66

16 Answers16

841

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.

mjv
  • 73,152
  • 14
  • 113
  • 156
David Hedlund
  • 128,221
  • 31
  • 203
  • 222
  • 29
    PPL, be aware that his behavior is changing on 1.6 in favor of `prop()`, while `.attr()` will be restricted to actual attributes – Fabiano Soriani May 04 '11 at 23:27
  • 1
    So is it best to use plain JS here? – Doug Molineux Jun 10 '11 at 16:46
  • 15
    @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. – David Hedlund Jun 11 '11 at 02:31
  • @David Hedlund : I suppose you are implying that all major browsers handle this the same way as of today, right? – Shawn Nov 06 '12 at 15:58
  • 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. – qris Mar 15 '13 at 13:04
  • 2
    @qris: Your problem is probably somewhere else. [Simple demo, using jQuery 1.9](http://jsfiddle.net/CRszR/). Sure works in my Chrome. – David Hedlund Mar 15 '13 at 13:58
  • ASs of 2020, This is still working. your welcome XD – Jovylle Sep 23 '20 at 12:31
97

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("");
James Wiseman
  • 29,946
  • 17
  • 95
  • 158
  • 2
    .removeAttr is likely to cause problems. – Kzqai May 07 '13 at 21:30
  • Care to expand on how? Or provide a link? – James Wiseman May 08 '13 at 08:42
  • Yes, Kzqai, I am also curious my answer was down-voted for this as well. The documentation mentions no risk. – cjstehno May 08 '13 at 12:41
  • 1
    Relevant documentation is actually on the .prop() method: http://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... – Kzqai May 08 '13 at 17:09
  • 1
    ...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. – Kzqai May 13 '13 at 21:27
30

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.

cjstehno
  • 13,468
  • 4
  • 44
  • 56
  • Also, as one of the other answers mentions, you wont need the each function; you could just chain the removeAttr call to the selector. – cjstehno Jan 22 '10 at 13:55
  • 7
    NOTE: this response is from 2010. At that time, this was a valid and accepted approach. Since then it has become deprecated. – cjstehno Aug 26 '13 at 12:11
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;
    }
}})());
igor
  • 5,351
  • 2
  • 26
  • 22
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);
alkos333
  • 631
  • 6
  • 11
  • 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 : https://gist.github.com/eikes/9484101 – eikes Mar 11 '14 at 11:44
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 );
Laurynas
  • 3,829
  • 2
  • 32
  • 22
  • 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. – Simon Hürlimann Jun 28 '13 at 07:39
  • @alkos333 has a solution that seems to work with labels, too. – Simon Hürlimann Jun 28 '13 at 07:40
  • It dependends on how the labels are used, if they use IDs then @alkos333 code works, if the radio button is nested in the label, use this version: https://gist.github.com/eikes/9484101 – eikes Mar 11 '14 at 11:43
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');
        }
    });
});
Andreas Louv
  • 46,145
  • 13
  • 104
  • 123
Sylvain Kocet
  • 181
  • 1
  • 2
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
                }
            });
        });
12

Try

$(this).attr("checked" , false );
rahul
  • 184,426
  • 49
  • 232
  • 263
11

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/

sebilasse
  • 4,278
  • 2
  • 37
  • 36
Almir Campos
  • 2,833
  • 1
  • 30
  • 26
7

Use this

$("input[name='nameOfYourRadioButton']").attr("checked", false);
CrsCaballero
  • 2,124
  • 1
  • 24
  • 31
7

You can use this JQuery for uncheck radiobutton

$('input:radio[name="IntroducerType"]').removeAttr('checked');
                $('input:radio[name="IntroducerType"]').prop('checked', false);
keivan kashani
  • 1,263
  • 14
  • 15
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

Jitendra Damor
  • 774
  • 17
  • 27
  • 2
    You realise that `$("input:radio").removeAttr("checked"); isn’t plain JavaScript, don’t you? – Manngo Jul 24 '23 at 02:27
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;

bummi
  • 27,123
  • 14
  • 62
  • 101
alecellis1985
  • 131
  • 2
  • 15
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

Menotti
  • 19
  • 1
-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.

William Isted
  • 11,641
  • 4
  • 30
  • 45