91

What method would be best to use to selectively set a single or multiple radio button(s) to a desired setting with JavaScript?

Mark Burgoyne
  • 1,524
  • 4
  • 18
  • 31

9 Answers9

147

Very simple

radiobtn = document.getElementById("theid");
radiobtn.checked = true;
Starx
  • 77,474
  • 47
  • 185
  • 261
  • Sweet - nice and easy thankyou. If I was to try to modify a nuber of radio buttons with sequential id's radio1, radio2 etc, then it might be ...... function check_radio() { for (var i = 1, radiobtn; radiobtn = document.getElementById("radio" + i); ++i) radiobtn.checked = true; } – Mark Burgoyne Feb 28 '12 at 10:15
  • I think `radiobtn.checked` should receive `'checked'` instead of `true`, although i can't remember where i read this. – Rafael Barros Nov 25 '13 at 17:35
  • 10
    @RafaelBarros, you're confusing the Javascript-property `.checked` with the xhtml-attribute `checked="checked"`. Since xhtml tried to be xml-compliant, no attributes without value were allowed (in contrast to html 4 or 5 where `` is correct syntax). Regardless of which mark-up language you're using, Javascript is Javascript and in Javascript objects have properties which could very well be a boolean value. Indeed, the DOM object associated with `` has a property `.checked` which can be `true` or `false`. – asontu Apr 28 '14 at 13:18
  • 5
    I suggest to add `var` before `radiobtn = ...` to avoid having it in the global scope. – Sandro Aug 30 '16 at 17:33
  • If you're using another button to activate it, it's even simpler: just include `onclick="theid.checked=true"` in the input tag of the activating button. – Aidan Stanger Mar 04 '21 at 04:42
47

the form

<form name="teenageMutant">
  <input value="aa" type="radio" name="ninjaTurtles"/>
  <input value="bb" type="radio" name="ninjaTurtles"/>
  <input value="cc" type="radio" name="ninjaTurtles" checked/>
</form>

value="cc" will be checked by default, if you remove the "checked" non of the boxes will be checked when the form is first loaded.

document.teenageMutant.ninjaTurtles[0].checked=true;

now value="aa" is checked. The other radio check boxes are unchecked.

see it in action: http://jsfiddle.net/yaArr/

You may do the same using the form id and the radio button id. Here is a form with id's.

<form id="lizardPeople" name="teenageMutant">
  <input id="dinosaurs" value="aa" type="radio" name="ninjaTurtles"/>
  <input id="elephant" value="bb" type="radio" name="ninjaTurtles"/>
  <input id="dodoBird" value="cc" type="radio" name="ninjaTurtles" checked/>
</form>

value="cc" is checked by default.

document.forms["lizardPeople"]["dinosaurs"].checked=true;

now value="aa" with id="dinosaurs" is checked, just like before.

See it in action: http://jsfiddle.net/jPfXS/

gaby de wilde
  • 1,313
  • 12
  • 6
21

You can also explicitly set value of radio button:

<form name="gendersForm">
  <input type="radio" name="gender" value="M" /> Man
  <input type="radio" name="gender" value="F" /> Woman
</form>

with the following script:

document.gendersForm.gender.value="F";

and corresponding radio button will be checked automatically.

Look at the example on JSFiddle.

sbrbot
  • 6,169
  • 6
  • 43
  • 74
20

Vanilla Javascript:

yourRadioButton.checked = true;

jQuery:

$('input[name=foo]').prop('checked', true);

or

$("input:checkbox").val() == "true"
Damien
  • 1,140
  • 15
  • 22
Justin Helgerson
  • 24,900
  • 17
  • 97
  • 124
  • Thanks - yes I had checked and found a number of different methods. Unfortunatley after a trying a few I was not having much success. Appreciate your time – Mark Burgoyne Feb 28 '12 at 10:13
  • @vinomarky - The thought crossed my mind, but I didn't want to come across as a bully. I don't actually care that much if a question is posted here that can be found elsewhere. – Justin Helgerson Feb 28 '12 at 14:45
  • @vinomarky : i still not get why u delete my post as ur qus posted get negative point. – Deepakmahajan Jul 04 '12 at 12:19
  • @Deepakmahajan: Sorry, have no idea of what you refer to. I have never deleted anyones posts, in fact I dont even think I have priviledge to do so even if I wanted to – Mark Burgoyne Jul 05 '12 at 13:00
  • Your Vanilla Javascript `yourRadioButton.checked` looks tempting but is not recommended in [this SO post](http://stackoverflow.com/questions/3434278/ie-chrome-are-dom-tree-elements-global-variables-here) – andruso Jul 07 '13 at 06:54
  • 1
    It's actually funny, because I am sure I've used that 2nd jQuery method with `[0]`, `[1]`, `[2]`, etc. after the `$(...)` part of it to do this before, but when I just tried `$('input[name=foo]')[0].attr('checked', true);` I got `Object doesn't support this property or method`. Same thing if I put `('checked', 'checked')`. But when I mixed the JavaScript with the jQuery option and did `$('input[name=foo]')[0].checked = true;` it set just fine. Odd. – vapcguy Mar 21 '15 at 00:37
  • You should be using `prop()` instead of `attr()` for setting boolean values. – Damien Sep 20 '16 at 02:25
11
/**
 * setCheckedValueOfRadioButtonGroup
 * @param {html input type=radio} vRadioObj 
 * @param {the radiobutton with this value will be checked} vValue 
 */
function setCheckedValueOfRadioButtonGroup(vRadioObj, vValue) {
    var radios = document.getElementsByName(vRadioObj.name);
    for (var j = 0; j < radios.length; j++) {
        if (radios[j].value == vValue) {
            radios[j].checked = true;
            break;
        }
    }
}
Luigi D'Amico
  • 665
  • 7
  • 11
4

Try

myRadio.checked=true
<input type="radio" id="myRadio">My radio<br>
Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
2

I am configuring a radio button within a document fragment and tried using radiobtn.checked = true;.

That didn't work so I instead went with this solution:

radiobtn.setAttribute("checked", "checked");
NuclearPeon
  • 5,743
  • 4
  • 44
  • 52
2
$("#id_of_radiobutton").prop("checked", true);
Dharman
  • 30,962
  • 25
  • 85
  • 135
Prajakta Kale
  • 392
  • 3
  • 19
0

This sets checked using name to cycle through the elements and a value check to set the desired element to true. I kept it as simple as possible, its pretty easy to put it into a function or a loop, etc.

variable 'nameValue' is the radio elements name value

variable 'value' when matched sets the radio button

Array.from(  document.querySelectorAll('[name="' + nameValue + '"]')   ).forEach((element,index) =>
                {
                    if (value === element.value) {
                        element.checked = true;
                    } else {
                        element.checked = false;
                    }
                });
Rumments
  • 11
  • 1