使用jquery添加图像输入,限制为4

时间:2012-06-11 19:16:54

标签: javascript jquery

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

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

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

由于

1 个答案:

答案 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--; 
    }
}