Check a radio button with javascript
Asked Answered
A

7

144

For some reason, I can't seem to figure this out.

I have some radio buttons in my html which toggles categories:

<input type="radio" name="main-categories" id="_1234" value="1234" /> // All
<input type="radio" name="main-categories" id="_2345" value="2345" /> // Certain category
<input type="radio" name="main-categories" id="_3456" value="3456" /> // Certain category
<input type="radio" name="main-categories" id="_4567" value="4567" /> // Certain category

The user can select whichever he/she wants, but when an certain event triggers, I want to set 1234 to be set checked radio button, because this is the default checked radio button.

I have tried versions of this (with and without jQuery):

document.getElementById('#_1234').checked = true;

But it doesn't seem to update. I need it to visibly update so the user can see it. Can anybody help?

EDIT: I'm just tired and overlooked the #, thanks for pointing it out, that and $.prop().

Anergy answered 16/1, 2014 at 16:5 Comment(6)
Check this StackOverflow question: [How to check a radio button with jQuery][1] [1]: #5666415Endocardial
change to document.getElementById('_1234').checked = true;Wilcher
@Wilcher without the #Phifer
Sorry, just a wrong copy-paste. Updated now. @FelipeKM Then please help me, I've not found one that helps.Anergy
@kjelelokk check my comment or Pointys answerWilcher
how do you wanna select a element by ID passing the wrong id? Remove this '#' before '_1234', this is for query selectors such jQuery $('#_1234')Outcry
T
235

Do not mix CSS/JQuery syntax (# for identifier) with native JS.

Native JS solution:

document.getElementById('_1234').checked = true;

To also trigger the associated event (e.g. if related controls need to be shown/hidden), call click():

document.getElementById('_1234').click();

JQuery solution:

$('#_1234').prop('checked', true);
Trimaran answered 16/1, 2014 at 16:9 Comment(6)
Technically it's CSS selector syntax. jQuery just borrowed and extended itPhifer
jQuery got it from querySelector I would imagine.Yippie
much better than .attr("checked", "checked")Query
@Yippie - Sizzle was used in jQuery from early 2006 onwards. (en.wikipedia.org/wiki/JQuery#History). querySelector wasn't shipped in browsers until 2009 and wasn't being used widely by developers until some time after that. I've never used jQuery all that much, but it significantly impacted on the evolution of JS.Paregoric
this sets the check box but doesn't necessarily trigger the associated event. what event is triggered when the user clicks a radio button?Dorthydortmund
@Dorthydortmund Yes, as this only changes the checked property of the radio button and does not perform a click, change or any other event. If you were to use checkboxSelector.click(), that would be where you would trigger a click event.Rosalba
C
26

If you want to set the "1234" button, you need to use its "id":

document.getElementById("_1234").checked = true;

When you're using the browser API ("getElementById"), you don't use selector syntax; you just pass the actual "id" value you're looking for. You use selector syntax with jQuery or .querySelector() and .querySelectorAll().

Careworn answered 16/1, 2014 at 16:7 Comment(2)
everyone is getting the element by ID I have more than one radio buttons with the same name. and I think that's what most people need to select a group of radios by name and then based on value check one of them.Uniform
@NadeemGorsi the "id" attribute cannot be shared by more than one element. All "id" values must be unique on a given page.Careworn
H
21

Today, in the year 2016, it is safe to use document.querySelector without knowing the ID (especially if you have more than 2 radio buttons):

document.querySelector("input[name=main-categories]:checked").value
Highchair answered 25/9, 2016 at 14:10 Comment(3)
OK, but how can I get the reverse effect or check a radio based on value.. and that's what question was about in fact.Uniform
@NadeemGorsi I provided an answer to select or "check" a radio button using QuerySelectorMisguidance
TechNerdXp Try selecting by value instead of name. document.querySelector('input[value="xyz"])Halberd
G
6

Easiest way would probably be with jQuery, as follows:

$(document).ready(function(){
  $("#_1234").attr("checked","checked");
})

This adds a new attribute "checked" (which in HTML does not need a value). Just remember to include the jQuery library:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
Gorga answered 16/1, 2014 at 17:6 Comment(1)
Or just $("#_1234").prop("checked", true)Rosalba
B
4

By using document.getElementById() function you don't have to pass # before element's id.

Code:

document.getElementById('_1234').checked = true;

Demo: JSFiddle

Barron answered 16/1, 2014 at 16:10 Comment(0)
M
3

I was able to select (check) a radio input button by using this Javascript code in Firefox 72, within a Web Extension option page to LOAD the value:

var reloadItem = browser.storage.sync.get('reload_mode');
reloadItem.then((response) => {
    if (response["reload_mode"] == "Periodic") {
        document.querySelector('input[name=reload_mode][value="Periodic"]').click();
    } else if (response["reload_mode"] == "Page Bottom") {
        document.querySelector('input[name=reload_mode][value="Page Bottom"]').click();
    } else {
        document.querySelector('input[name=reload_mode][value="Both"]').click();
    }
});

Where the associated code to SAVE the value was:

reload_mode: document.querySelector('input[name=reload_mode]:checked').value

Given HTML like the following:

    <input type="radio" id="periodic" name="reload_mode" value="Periodic">
    <label for="periodic">Periodic</label><br>
    <input type="radio" id="bottom" name="reload_mode" value="Page Bottom">
    <label for="bottom">Page Bottom</label><br>
    <input type="radio" id="both" name="reload_mode" value="Both">
    <label for="both">Both</label></br></br>
Misguidance answered 25/2, 2020 at 19:41 Comment(0)
U
2

It seems the item.checked property of a HTML radio button cannot be changed with JavaScript in Internet Explorer, or in some older browsers.

I also tried setting the "checked" attribute, using: item.setAttribute("checked", ""); I know the property can be set by default, but I need just to change the checked attribute at runtime.

As a workarround, I found another method, which could be working. I had called the item.click(); method of a radio button. And the control has been selected. But the control must be already added to the HTML document, in order to receive the click event.

Unreal answered 20/1, 2022 at 17:37 Comment(2)
Nice detail Adrian, but I think the original poster had a much simpler question with a "#" in the wrong place :)Mooney
Thanks for the tip with item.click()Remembrancer

© 2022 - 2024 — McMap. All rights reserved.