0

我有这个代码,用户可以上传图片。它工作得很好,但用户可以提交无限的图片,我想限制为四个。

当用户到达四个输入字段时,将不允许他们添加任何输入。

     <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>

谢谢

4

1 回答 1

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--; 
    }
}
于 2012-06-11T19:38:25.553 回答