【发布时间】:2017-09-01 16:09:36
【问题描述】:
我有一个简单的表格,其中包含三个输入字段(文本、日期和下拉菜单),单击“添加行”按钮后,将添加新行。但是我需要对输入字段执行以下验证;如果输入字段为空,则不应添加新行,并且应引发错误消息。如何实现?
添加新行和删除选定行的功能:
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
for (var i = 0; i < colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[0].cells[i].innerHTML;
//alert(newcell.childNodes);
switch (newcell.childNodes[0].type) {
case "text":
newcell.childNodes[0].value = "";
break;
case "checkbox":
newcell.childNodes[0].checked = false;
break;
case "select-one":
newcell.childNodes[0].selectedIndex = 0;
break;
}
}
}
function deleteRow(tableID) {
try {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
for (var i = 0; i < rowCount; i++) {
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
if (null != chkbox && true == chkbox.checked) {
if (rowCount <= 1) {
alert("Cannot delete all the rows.");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
} catch (e) {
alert(e);
}
}
body {
font-family: "Open Sans", Helvetica, Arial, sans-serif;
font-weight: 300;
font-size: 12px;
line-height: 30px;
color: #777;
background: #366161;
}
#dataTable {
margin: 0 auto;
margin-top: 30px;
}
.btn {
-webkit-border-radius: 5;
-moz-border-radius: 5;
border-radius: 5px;
font-family: Arial;
color: #ffffff;
font-size: 15px;
background: #2f354a;
padding: 7px 15px 7px 15px;
text-decoration: none;
outline: none;
margin: 30px;
}
.btn:hover {
background: #3cb0fd;
text-decoration: none;
}
.btn_container {
margin: 0 auto;
width: 360px;
}
select option[value="red"] {
background-color: #f00;
}
select option[value="yellow"] {
background-color: #FFFF00;
}
select option[value="green"] {
background-color: #7CFC00;
}
h1.heading {
text-align: center;
color: #ffffff;
}
#errors {
margin-left: 310px;
color: red;
font-size: 16px;
}
<body>
<h1 class="heading"> Simple Form</h1>
<table id="dataTable" width="900px" cellspacing="5" cellpadding="10" style="background:#F0F8FF;border:1px dotted">
<tr>
<td><input type="checkbox" name="chk" /></td>
<td> Name : <input type="text" name="txt" id="fname" placeholder="Enter your name" required/></td>
<td>Date: <input type="date" name="date" id="delivery_date" required/></td>
<td>
Color:
<select name="Color" required>
<option value="red">Red</option>
<option value="yellow">yellow</option>
<option value="green">Green</option>
</select>
</td>
</tr>
</table>
<div class="btn_container">
<input type="button" class="btn" value="Add Row" onclick="addRow('dataTable')" />
<input type="button" class="btn" value="Delete Row" onclick="deleteRow('dataTable')" />
</div>
</body>
【问题讨论】:
-
所以你只想在当前行包含有效输入的情况下添加一个新行?
-
是的,你是对的..你能帮帮我吗...
-
没问题,请看下面我的回答。
标签: javascript html validation input