我有一個帶有三個輸入字段(文本,日期和下拉列表)的簡單表格,點擊「添加行」按鈕後,新行被添加。不過,我需要在輸入字段上執行下面的驗證;如果輸入字段爲空並且應該引發錯誤消息,則不應添加新行。如何實現這一目標?如何執行輸入字段驗證並防止在字段爲空時添加新行?
功能來添加新行,並刪除選定行:
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>
所以,你只需要在當前行包含有效輸入來添加一個新行? – freginold
是的,你是對的..請你幫我解決...... – Vivek
當然,請看下面的答案。 – freginold