js输入框输入点击按钮添加表单元素
作者:互联网
添加表单元素
html
<div id="form">
请输入姓名: <input type="text" id="name"> <br>
请输入性别: <input type="radio" id="sex" name="sex" checked>男
<input type="radio" name="sex">女<br>
请输入年龄: <input type="text" id="age">
<button>添加到表格</button>
</div>
<table id="tab">
<thead>
<tr>
<th width="20%"><input type="checkbox" id="all">全选</th>
<th>姓名</th>
<th>性别</th>
<th>年龄</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="checkbox"></td>
<td>张三</td>
<td>女</td>
<td>88</td>
</tr>
<tr>
<td><input type="checkbox"></td>
<td>李四</td>
<td>男</td>
<td>18</td>
</tr>
<tr>
<td><input type="checkbox"></td>
<td>王五</td>
<td>女</td>
<td>1</td>
</tr>
</tbody>
</table>
<div id="div1">
<button>删除所选行</button>
</div>
css
#form{width: 480px;margin: 30px auto;border: 1px solid #eee;border-radius: 5px;padding: 10px;line-height: 30px;position: relative;}
button{position: absolute;right: 10px;bottom: 10px;}
#tab{width: 500px;margin: 30px auto;border-collapse: collapse;}
th,td{border: 1px solid #000;padding: 5px;}
tbody tr td:first-child{text-align: center;}
/*input[type] 属性选择器 选择input标签,并且有type属性input标签*/
/*input[type = "checkbox"] 选择有type属性并且值为checkbox的input标签*/
input[type="checkbox"]{width: 15px;height: 15px;}
#div1{position: relative;width: 480px;padding: 10px;margin: 0 auto;}
js
var oInput = document.getElementById("form").getElementsByTagName("input");
var oBut = document.getElementsByTagName("button");
var oTable = document.getElementsByTagName("table")[0];
var tBodies = oTable.tBodies[0];
var allBut = document.getElementById("all");
//2.点击添加到表格,获取输入框中的内容,在表格中添加一行
oBut[0].onclick = function () {
//1.创建行
var tr = document.createElement("tr");
//3.添加单元格
tr.appendChild(createNode("td","<input type='checkbox' />"));
tr.appendChild(createNode("td", oInput[0].value));
tr.appendChild(createNode("td",oInput[1].checked == true?"男":"女"));
tr.appendChild(createNode("td", oInput[3].value));
//2.添加行到表格
tBodies.appendChild(tr);
checkAll();
}
function createNode(element,text) {
var td = document.createElement(element);
td.innerHTML = text;
return td;
}
//3.删除
oBut[1].onclick = function () {
for(var i = 0;i<tBodies.rows.length;i++){
var oIn = tBodies.rows[i].getElementsByTagName("input")[0];
if(oIn.checked == true){ //是选中
tBodies.rows[i].remove();
i--;
}
}
}
//4.点击全选按钮,全选下面所有的input
allBut.onclick = function () {
var oI = tBodies.getElementsByTagName("input");
console.log(oI);
for(var i = 0;i<oI.length;i++){
oI[i].checked = allBut.checked;
}
}
//5.全部选中input时,全选
checkAll();//一开始就应该初始化
function checkAll () {
var oI = tBodies.getElementsByTagName("input");
for(var i = 0;i<oI.length;i++){
oI[i].onclick = function () {
//假设全选了,然后去循环验证假设是否成立,
//如果有任何一个input没有被选中,假设不成立,则为false
var tr = true; //假设
for(var j = 0;j<oI.length;j++){
if(oI[j].checked == false){
tr = false;
break;
}
}
allBut.checked = tr;
}
}
}
}
效果图
标签:document,createNode,tr,表单,输入框,var,input,td,js 来源: https://blog.csdn.net/style201904/article/details/90450309