100

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

2
  • 1
    @Starx - jQuery took care of my most recent rash; surely it can check radio buttons! Commented Feb 28, 2012 at 5:02
  • 9
    @RintoGeorge, I agree, i love jQuery too, but this is too simple. We dont need jQuery for this. Commented Feb 28, 2012 at 5:04

9 Answers 9

160

Very simple

radiobtn = document.getElementById("theid");
radiobtn.checked = true;
Sign up to request clarification or add additional context in comments.

5 Comments

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; }
I think radiobtn.checked should receive 'checked' instead of true, although i can't remember where i read this.
@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 <sometag checked> 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 <input type="radio" /> has a property .checked which can be true or false.
I suggest to add var before radiobtn = ... to avoid having it in the global scope.
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.
48

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/

Comments

26

You can also explicitly set value of radio button with the following script:

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

and corresponding radio button will be checked automatically.

1 Comment

Works perfect until you try it in IE <.<
20

Vanilla Javascript:

yourRadioButton.checked = true;

jQuery:

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

or

$("input:checkbox").val() == "true"

7 Comments

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
@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.
@vinomarky : i still not get why u delete my post as ur qus posted get negative point.
@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
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.
|
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;
        }
    }
}

Comments

3

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");

2 Comments

You can also use radiobtn.setAttribute("checked", ""); to select it.
This is what works if you are using Stimulus in 2023.
3

Try

myRadio.checked=true
<input type="radio" id="myRadio">My radio<br>

Comments

1
$("#id_of_radiobutton").prop("checked", true);

2 Comments

This is jQuery, not JavaScript, innit?
Well, jQuery is JavaScript … but if you're going to introduce a third party library to solve a problem then you should at least explain that you are doing so (and preferably justify it … which would be hard for something this trivial even in 2018).
1

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;
                    }
                });

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.