Ответ 1
Просто установите для свойства checked
значение true
:
document.getElementById(shirtColor).checked = true;
Здесь скрипка: http://jsfiddle.net/akkSY/
Есть ли способ установить отмеченный переключатель с помощью переменной JavaScript? Я надеялся, что смогу получить переключатель по ID и обновить проверенную радио.
<!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>
Просто установите для свойства checked
значение true
:
document.getElementById(shirtColor).checked = true;
Здесь скрипка: http://jsfiddle.net/akkSY/
Это будет выглядеть как
btn = document.getElementById("itsID");
btn.checked = true;
вы можете использовать jquery таким образом
$("control_id").attr("checked",true);
убедитесь, что элемент загружен до запуска этого jquery. Чтобы быть в безопасности, вы всегда должны ставить скрипты в конце страницы перед тегом </body>