Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set Checked Radio Button Using a JavaScript Variable

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>
like image 774
user1822824 Avatar asked Jan 30 '13 20:01

user1822824


1 Answers

Just set its checked property to true:

document.getElementById(shirtColor).checked = true;

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

like image 124
Joseph Silber Avatar answered Nov 09 '22 23:11

Joseph Silber