我有这个代码,用户可以上传图片。它工作正常,但用户可以提交无限制的图片,我想限制为四。
当用户到达四个输入字段时,将不允许他们添加任何输入。
<script type="text/javascript">
function addItems()
{
var table1 = document.getElementById('tab1');
var newrow = document.createElement("tr");
var newcol = document.createElement("td");
var input = document.createElement("input");
input.type="file";
input.name="image[]";
newcol.appendChild(input);
newrow.appendChild(newcol);
table1.appendChild(newrow);
}
function remItems()
{
var table1 = document.getElementById('tab1');
var lastRow = table1.rows.length;
if(lastRow>=2)
table1.deleteRow(lastRow-1);
}
</script>
<form method="post" action="" enctype="multipart/form-data">
<table align="center" border="0" id="tab1">
<tr>
<td width="218" align="center">
<input type="file" name="image[]" /></td>
<td width="54" align="center">
<img src="Button-Add-icon.png" alt="Add" style="cursor:pointer"
onclick="addItems()" /></td>
<td>
<img src="Button-Delete-icon.png" alt="Remove" style="cursor:pointer"
onclick="remItems()" /></td>
</tr>
</table>
<table align="center" border="0" id="tab2">
<tr><td align="center">
<input type="submit" value="Upload" name="upload" /></td></tr>
</table>
</form>
由于
答案 0 :(得分:0)
添加一个全局计数器..并检查您的addItems
函数..例如:
var totalItems = 0;
function addItems()
{
if(totalItems < 4) {
var table1 = document.getElementById('tab1');
var newrow = document.createElement("tr");
var newcol = document.createElement("td");
var input = document.createElement("input");
input.type="file";
input.name="image[]";
newcol.appendChild(input);
newrow.appendChild(newcol);
table1.appendChild(newrow);
totalItems++; //increment the global counter...
} else {
//Display your message here.. with an alert or something...
}
}
function remItems()
{
var table1 = document.getElementById('tab1');
var lastRow = table1.rows.length;
if(lastRow>=2) {
table1.deleteRow(lastRow-1);
totalItems--;
}
}