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>
Just set its checked
property to true
:
document.getElementById(shirtColor).checked = true;
Here's the fiddle: http://jsfiddle.net/akkSY/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With