获取上传字段的值并计算数组

时间:2011-11-06 15:28:31

标签: javascript html forms

我有以下HTML代码:

<form name="uploadForm" action="" method="POST" enctype="multipart/form-data">
<input type="file" name="file_sub[]" />
<input type="file" name="file_sub[]" />
<input type="file" name="file_sub[]" />
<input type="file" name="file_sub[]" />
<input type="file" name="file_sub[]" />
<input type="button" onClick="javascript:submitform();" value="SUBMIT BTN" />
</form>

这里是javascript函数submitform()

function submitform()
{
var minUpload = 1;
var uploadNo;
var count=document.uploadForm.file_sub.length;
for(a=0;a<count;a++)
        {

           if(document.uploadForm.file_sub.value != '')
               {
                 uploadNo++;
               }

         }

    if(uploadNo > minUpload){   
  document.uploadForm.submit();
    }else{
        alert('Please Upload Atleast ' + minUpload + ' files');
    }

}

javascript假设验证并确保文件的至少minUpload字段中的文件。

但由于某种原因,当我尝试在函数中获取文件的长度时,我得到一个错误(根据chrome的调试器,我得到“Uncaught TypeError:无法读取未定义的属性'长度')但是我用复选框尝试了同样的事情,它工作得很好。我究竟做错了什么?甚至可以在js中完成这样的任务吗?

1 个答案:

答案 0 :(得分:3)

您必须参考file_sub[]。固定功能:

var count = document.uploadForm["file_sub[]"].length;

function submitform(){
    var minUpload = 1;
    var uploadNo;
    var files = document.forms['uploadForm']["file_sub[]"];
    var count = files.length;
    for(var a=0; a<count; a++){
        if(files[a].value != ''){
            uploadNo++;
        }
    }

    if(uploadNo > minUpload){   
        document.forms['uploadForm'].submit();
    } else {
        alert('Please Upload Atleast ' + minUpload + ' files');
    }
}