我有一个表单,有多个相同的字段,例如:数量、零件编号、制造价格及以下将是5行,我想将其减少到1行,并让用户可以选择在需要时添加带有多列的额外行。这是必须用JavaScript完成的吗?我能不能有一个小按钮,点击这里添加额外的行?
我试过了,但它没有添加任何字段:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<link href="/style.css" rel="stylesheet" type="text/css" />
<title>More form fields</title>
<script type="text/javascript">
FUNCTION addRowToTable()
{
VAR tbl = document.getElementById('tblAddress');
VAR lastRow = tbl.rows.length;
// if there's no header row in the table, then iteration = lastRow + 1
VAR iteration = lastRow;
// var iteration = lastRow + 1;
VAR row = tbl.insertRow(lastRow);
// cell 0
VAR cell0 = row.insertCell(0);
VAR el = document.createElement('input');
el.type = 'text';
el.NAME = 'Address[]';
el.size = 30;
cell0.appendChild(el);
//cell 1
VAR cell1 = row.insertCell(1);
VAR el = document.createElement('input');
el.type = 'text';
el.NAME = 'City[]';
el.size = 10;
cell1.appendChild(el);
//cell 2
VAR cell2 = row.insertCell(2);
VAR el = document.createElement('input');
el.type = 'text';
el.NAME = 'State[]';
el.size = 2;
cell2.appendChild(el);
//cell 3
VAR cell3 = row.insertCell(3);
VAR el = document.createElement('input');
el.type = 'text';
el.NAME = 'Zip[]';
el.size = 5;
cell3.appendChild(el);
}
</script>
</head>
<body>
<h3>Dynamic add form fields</h3>
<form action="Untitled-2.php" name="h" method="post">
<table id="tblAddress">
<tr>
<td class="txtBase">Address</td>
<td class="txtBase">City</td>
<td class="txtBase">State</td>
<td class="txtBase">Zip</td>
</tr>
<tr>
<td><input name="Address[]" type="text" size="30" maxlength="255"></td>
<td><input name="City[]" type="text" size="10" maxlength="255"></td>
<td><input name="State[]" type="text" size="2" maxlength="10"></td>
<td><input name="Zip[]" type="text" size="5" maxlength="25"></td>
</tr>
</table>
<input type="button" name="Add" value="Add" onClick="addRowToTable();"/>
<input type="submit" name="Submit" value="Submit" />
</form>
</body>
</html>
这里是使用jQuery> 1.7的稍微不那么冗长的版本,它优先使用on()方法进行事件绑定:
http://jsfiddle.net/tZPg4/5077/<form>
<input type="text" />
</form>
<button id="addFields">Add another field</button>
<script>
$(function ($) {
$('body').on("click", '#addFields', function () {
$('form').append('<input type="text" />');
})
})(jQuery);
</script>
您可以使用javascript或php来完成。
Javascript在各个方面都更快更好,而且每次你需要添加一个字段时,它都不会触及服务器。
Php每次需要添加字段时都需要刷新页面,并且是在服务器端完成的,这将增加服务器上的负载。您只需要在每次需要添加或删除字段时重新构建表单。不要忘记重新填充已经填充的表单字段。
使用jquery可以做到这一点…
<div id="pricecontainer"></div>
<a id="addprice" href="javascript::void(0)">Add More</a>
<script>
$('#addprice').click(function(){
$len= $("#pricecontainer").children("div").length;
$("#pricecontainer").append("<div class='FormWrap PriceBorder' id='"+$len+"'><div class='input text'><label>Price</label><input style='width: 100px;' class='price' type='text' name='price[]' id='price"+$len+"' maxlength='5'></div></div>");
});
</script>