js获取表单各行各列的值,包括input文本框和单选按钮
程序员文章站
2022-03-04 16:13:21
...
最近所做的项目需要取出table中各行各列的数据进行操作,因为一些原因,没有找到什么好方法,只能用js来操作.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript">
function show() {
var tab = document.getElementById("test");
//表格行对象
var rows = tab.rows;
for(var i = 1; i < rows.length; i++) { //遍历表格的行
for(var j = 0; j < rows[i].cells.length; j++) { //遍历每行的列
if(j == 0) {
var obj = rows[i].cells[j].getElementsByTagName("INPUT") //获取单选框的值
for(var z = 0; z < obj.length; z++) {
if(obj[z].checked) {
//alert("单选 z=" + z + "i=" + i + "j=" + j + ":" + obj[z].value);
alert("第" + (i + 1) + "行,第" + (j + 1) + "列的值是:" + obj[z].value);
}
}
}else if(j==3){
//innerHTML
alert("第" + (i + 1) + "行,第" + (j + 1) + "列的值是:" + rows[i].cells[j].innerHTML);
}else{
alert("第" + (i + 1) + "行,第" + (j + 1) + "列的值是:" + rows[i].cells[j].getElementsByTagName("INPUT")[0].value);
}
}
}
}
</script>
</head>
<body>
<table id="test" border="1">
<tr>
<td>性别</td>
<td>姓名</td>
<td>年纪</td>
<td>评语</td>
</tr>
<tr>
<td>
<input type="radio" name="radio" value="是" />是
<input type="radio" name="radio" value="否" />否
<input type="radio" name="radio" value="免" />免
</td>
<td><input type="text" /></td>
<td><input type="text" /></td>
<td>成绩优良</td>
</tr>
</table>
<input type="button" onclick="show();" value="查看" />
</body>
</html>