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/

Sign up to request clarification or add additional context in comments.

1 Comment

@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.
3

It would look like that

btn = document.getElementById("itsID");
btn.checked = true;

1 Comment

Probably because you have to put shirtColor instead of itsID, 'itsID' was used as an example
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

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.