我是jquery / javascript的新手,现在我有一个表单,用户可以在其中上传多个文件,这工作得很好,但是我需要对其进行更改,这是工作代码。
$('#userFiles').change(function() {
var combinedSize = 0;
for (var i = 0; i < this.files.length; i++) {
combinedSize += (this.files[i].size || this.files[i].fileSize);
}
if (combinedSize > 104857600) {
toastr["error"]("Max upload size is 100MB");
}
});
的HTML
<input type="file" class="form-control" id="userFiles" name="userFiles[]" multiple/>
现在,我想做的是在提交检查之前,如果集合文件的大小大于100(如果是),则停止提交表单,并显示一个错误,您不能上传超过100MB的错误,因为这是更新的代码。
$("form").on("submit", function(e) {
e.preventDefault();
$('#userFiles').change(function() {
var combinedSize = 0;
for (var i = 0; i < this.files.length; i++) {
combinedSize += (this.files[i].size || this.files[i].fileSize);
}
if (combinedSize > 104857600) {
toastr["error"]("Max upload size is 100MB");
}
});
});
我的问题是,它使用此功能是因为它是表单提交时输入更改的事件,我无法在其中使用其他事件,我希望逻辑仅在表单提交上起作用,我如何用userFile id属性替换它?我尝试了几种方法,但是没有用。
function validateMaxFileSize() {
//get the files off of the element
var files = $('#userFiles').prop('files');
var combinedSize = 0;
for (var i = 0; i < files.length; i++) {
combinedSize += (files[i].size || files[i].fileSize);
}
//return true if the max is exceeded
return (combinedSize > 104857600);
}
$('#userFiles').change(function() {
//if the max is exceeded, show toaster
if (validateMaxFileSize()) {
toastr["error"]("Max upload size is 100MB");
}
});
$("form").on("submit", function(e) {
//if the max is exceeded, cancel the submit
if (validateMaxFileSize()) {
e.preventDefault();
toastr["error"]("Max upload size is 100MB");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" class="form-control" id="userFiles" name="userFiles[]" multiple/>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句