我想实现的效果是:在多个上传文件时,单击添加何以增加一个文件上传域,单击删除可以删除一个文件上传域。用js实现的代码:
<script type="text/javascript">
function insertRow(){
var rowindex = document.all("addordel").length;
if(rowindex>=5){
alert("一次只能上传5个文件!");
return false;
}
var obj = document.getElementsByName("addordel")[0].cloneNode(true);
document.all("change").appendChild(obj);
//document.getElementsByName("change").appendChild(obj);
}
function delRow(){
var allrows = document.all("addordel");
var rowindex = document.all("addordel").length;
if(rowindex>=2){
// event.srcElement.parentNode.removeNode(true); 这是在IE下的方式
// event.target.parentNode.removeChild(true);
document.getElementById("change").removeChild(allrows[allrows.length-1]);
}else{
alert("警告:最后一个不能删除!!");
}
}
function chkfile(){
var obj = document.getElementsByName("upfile[]");
num = obj.length;
for (i=0;i<num ;i++ )
{
if(obj[i].value == 0){
alert("请添加上传文件!");
return false;
}
}
}
</script>
另外在form表单中使用的是多文件上传,即采用数组的形式:
<form method="post" action="upfile_chk.php" enctype="multipart/form-data">
<ul id="change">
<li id="addordel" name="addordel">
<input type="file" id="upname[]" name="upname[]" style="width:200px;background-color:#f0f0f0;"/>
<select id="foundtype[]" name="foundtype[]">
<?php
header("Content-Type:text/html;charset=gb2312");
$dsn = "mysql:host=localhost;dbname=db_upan";
$db = new PDO($dsn,"root","");
$typesql = "select * from tb_uptype";
$statement = $db->query($typesql);
while($result = $statement->fetch(PDO::FETCH_ASSOC )){
?>
<option value="<?php echo $result['genrename'];?>"><?php echo $result['genrename']; ?></option>
<?php
}
?>
</select>
<!-- be sure the file is public or not -->
<select id="ispub[]" name="ispub">
<option value="0" selected="selected">不公开</option>
<option value="1">公开</option>
</select>
<!-- add upload area or del-->
<button onclick="delRow()" style="border:1px #000000 solid;background-color:#f0f0f0;" type="button">删除</button>
<button onclick="insertRow()" style="border:1px #000000 solid;background-color:#f0f0f0;" type="button">添加</button>
</li>
</ul>
<input type="submit" id="upbtn" name="upbtn" value="上传" onclick="return chkfile()" style="background-color:#f0f0f0;border:1px #000000 solid;"/>
</form>
其中:注意button中的type属性一定不要忘记设定为:type="button",因为button默认的是提交的,如果不设定这个属性,就会提交表单导致效果实现了只是刷新一下,不会实际的出现。还有注意在移除的时候的那种方式。