getElementsByName 的应用-获取radio button组的选择值
getElementsByName用来获取name一样的一组元素。
应用:
获取一组radio button 的选中值。
例子如下:
应用:
获取一组radio button 的选中值。
例子如下:
<html>
<head>
<title>getElementsByName Sample</title>
<script type="text/javascript" language="javascript">
function getColor() {
var oColors = document.getElementsByName("rdColor");
var color = "";
for (var i=0;i<oColors.length;i++) {
if (oColors[i].checked) {
color = oColors[i].value;
break;
}
}
if (color == "")
alert("Please choose a color!!");
else
alert("Your favorite color is: " + color);
}
</script>
</head>
<body>
<form action="javascript:getColor();" method="post">
<fieldset>
<legend>What color do you like?</legend>
<input type="radio" name="rdColor" value="red" /> Red <br />
<input type="radio" name="rdColor" value="green" /> Green <br />
<input type="radio" name="rdColor" value="blue" /> Blue <br />
</fieldset>
<input type="submit" value="Submit" />
</form>
</body>
</html>
<head>
<title>getElementsByName Sample</title>
<script type="text/javascript" language="javascript">
function getColor() {
var oColors = document.getElementsByName("rdColor");
var color = "";
for (var i=0;i<oColors.length;i++) {
if (oColors[i].checked) {
color = oColors[i].value;
break;
}
}
if (color == "")
alert("Please choose a color!!");
else
alert("Your favorite color is: " + color);
}
</script>
</head>
<body>
<form action="javascript:getColor();" method="post">
<fieldset>
<legend>What color do you like?</legend>
<input type="radio" name="rdColor" value="red" /> Red <br />
<input type="radio" name="rdColor" value="green" /> Green <br />
<input type="radio" name="rdColor" value="blue" /> Blue <br />
</fieldset>
<input type="submit" value="Submit" />
</form>
</body>
</html>
技术改变世界