当用户点击“保存”按钮时,我希望我的代码获取已检查的单选按钮值。我有代码布局,但我不确定如何循环通过单选按钮,因为他们没有类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>
saveButton.onclick = function() {
// Go through shirtColor rabio buttons to see which one is ticked
for (var i = 0; i < shirtColor.length; i++) {
if (.checked = true) {
// Set shirtColor variable to selected color
var shirtColor = .checked;
// Only one value can be selected so we're done
return;
}
}
};
</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>
<p>
<input type="button" id="saveButton" value="Save">
</p>
</body>
</html>
答案 0 :(得分:1)
使用普通Javascript ,您可以:
saveButton.onclick = function() {
// Go through shirtColor rabio buttons to see which one is ticked
var shirtColors = document.getElementsByName("shirtColor");
for (var i = 0; i < shirtColors.length; i++) {
var shirtColor = shirtColors[i];
if (shirtColor.checked) {
// Set shirtColor variable to selected color
alert(shirtColor.value);
// Only one value can be selected so we're done
return;
}
}
};
请参阅this Fiddle。
答案 1 :(得分:0)
你很亲密。您需要将其包装在<form>
中,以便为脚本提供一些上下文。在这种情况下,您不需要ID。
saveButton.onclick = function() {
var shirtColor = document.forms[0].shirtColor;
for (var i = 0; i < shirtColor.length; i++) {
if (shirtColor[i].checked == true) {
return shirtColor[i].value;
}
}
}
答案 2 :(得分:0)
您需要将for循环更改为
var cboxes = document.getElementsByName('shirtColor');
for(var i = 0; i < cboxes.length ; i++
{
if(cboxes[i].checked)
shirtColor = cboxes[i];
}
但是,如果你使用jquery,它会更简单:
var shirtColor = $("input[name='shirtColor']:checked").val();