<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<title>测试</title>
</head>
<body>
<form id="form1" name="form1">
文本框 :<input type="text" id="txt" value="txt" />
<br />
单选按钮:<input type="radio" value="男" name="sex" />男 <input type="radio" value="女" name="sex" checked="checked"/>女
<br />
复选框:<input type="checkbox" value="1" name="check[]"/>1<input type="checkbox" value="2" checked="checked" name="check[]" />2<input type="checkbox" value="3" checked="checked" name="check[]" />3
<br />
下拉框:
<select id="sel" style="width: 100px">
<option value="yi">1</option>
<option value="er" selected="selected">2</option>
<option value="san">3</option>
</select>
<br />
<input type="button" value="获取" onclick="getVal()"/>
</form>
<script type="text/javascript">
function getVal(){
var str="";
//获取单选按钮的值
var radios = document.form1.sex;
var n = radios.length;
for (var i = 0; i < n; i++) {
if (radios[i].checked) {
str = " 单选 "+radios[i].value;
}
}
//获取复选框中选中的值的组合 1,2,3,4
var checkboxs = document.getElementsByName('check[]');
var n = checkboxs.length;
for (var i = 0; i < n; i++) {
if (checkboxs[i].checked) {
str += " 复选框 "+checkboxs[i].value;
}
}
//获取下拉列表的选中项的值
//方法一:
str += " 列表 一:"+document.getElementById("sel").value;
//方法二:
var sel = document.getElementById("sel");
str += " 列表 二:"+sel.options[sel.selectedIndex].value;
alert(str);
}
</script>
</body>
</html>
JS获取表单元素的值
点赞
收藏