10

Is there a way to set the checked radio button using a JavaScript variable? I was hoping I could get the radio button by ID and update the checked radio.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>
<script>
var shirtColor = "green";

document.getElementById(shirtColor); 
</script>
</head>

<body>
<p>Shirt Color:
<input type="radio" name="shirtColor" id="red" value="red" />
Red
<input type="radio" name="shirtColor" id="green" value="green" />
Green
<input type="radio" name="shirtColor" id="blue" value="blue" /> 
Blue</p>
</body>
</html>

3 Answers 3

26

Just set its checked property to true:

document.getElementById(shirtColor).checked = true;

Here's the fiddle: http://jsfiddle.net/akkSY/

1
  • 7
    @user1822824 - You have to wait for the elements to be available. Put your script at the bottom of the body tag, after those elements are already on the page. Jan 30, 2013 at 20:24
3

It would look like that

btn = document.getElementById("itsID");
btn.checked = true;
1
  • Probably because you have to put shirtColor instead of itsID, 'itsID' was used as an example
    – igarcia
    Jan 30, 2013 at 20:24
2

you can use jquery in this way

$("control_id").attr("checked",true);

be sure that element is loaded before this jquery is executed.. to be safe you should always put scripts in the end of the page before </body> tag

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.