使用多个文件输入时如何限制选择的最大文件数

使用<input type="file" multiple>时,用户可以选择多个文件。

一个如何限制可以选择的文件数限制,例如两个?


小怪兽爱吃肉
浏览 1480回答 3
3回答

杨__羊羊

如果文件数大于max_file_number,这应该起作用并保护您的表单不被提交。$(function() {&nbsp; var // Define maximum number of files.&nbsp; &nbsp; &nbsp; max_file_number = 3,&nbsp; &nbsp; &nbsp; // Define your form id or class or just tag.&nbsp; &nbsp; &nbsp; $form = $('form'),&nbsp;&nbsp; &nbsp; &nbsp; // Define your upload field class or id or tag.&nbsp; &nbsp; &nbsp; $file_upload = $('#image_upload', $form),&nbsp;&nbsp; &nbsp; &nbsp; // Define your submit class or id or tag.&nbsp; &nbsp; &nbsp; $button = $('.submit', $form);&nbsp;&nbsp; // Disable submit button on page ready.&nbsp; $button.prop('disabled', 'disabled');&nbsp; $file_upload.on('change', function () {&nbsp; &nbsp; var number_of_images = $(this)[0].files.length;&nbsp; &nbsp; if (number_of_images > max_file_number) {&nbsp; &nbsp; &nbsp; alert(`You can upload maximum ${max_file_number} files.`);&nbsp; &nbsp; &nbsp; $(this).val('');&nbsp; &nbsp; &nbsp; $button.prop('disabled', 'disabled');&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; $button.prop('disabled', false);&nbsp; &nbsp; }&nbsp; });});
打开App,查看更多内容
随时随地看视频慕课网APP