JQuery 检查输入文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8628657/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 10:48:02  来源:igfitidea点击:

JQuery Check Input File

jqueryfile-uploadvalidation

提问by user1108996

I have file input fields in a group like below. I'd like all of them to be required fields.

我在如下组中有文件输入字段。我希望所有这些都是必填字段。

<!-- file upload group -->
<div class="Fieldset FileUpGroup">
  <span class="Legend">File Upload Group: (required)</span>
  <input name="fileUploads[]" type="file">
  <input name="fileUploads[]" type="file">
  <input name="fileUploads[]" type="file">
</div>

I have the following JQuery to validate, but it only validates the first one.

我有以下 JQuery 需要验证,但它只验证第一个。

$('.FileUpGroup').each(function() {
    if($(this).find('input[type=file]').val() == '') { 
        Response('- Upload file not selected!', true);
        $(this).addClass('Error').fadeOut().fadeIn();
        return false;
    }
    else {
        $(this).removeClass('Error');
    }
});

Thank You!

谢谢你!

回答by AlienWebguy

You're using each()on the wrong element:

您在each()错误的元素上使用:

$('input[type="file"]').each(function() {
    var $this = $(this);
    if ($this.val() == '') { 
        Response('- Upload file not selected!', true);
        $this.addClass('Error').fadeOut().fadeIn();
        return false;
    } else {
        $this.removeClass('Error');
    }
});

回答by marxus

.val()only returns the first value.
In your loop ($('.FileUpGroup').each)is only activated for one item... the DIV.FileUpGroupelement.
$('.FileUpGroup input[type=file]')will find all the items and then iterates them one at a time
Here is an example. Hope I have been useful.

.val()只返回第一个值。
在你的循环($('.FileUpGroup').each)中只为一项激活......DIV.FileUpGroup元素。
$('.FileUpGroup input[type=file]')将找到所有项目,然后一次迭代一个。
这是一个例子。希望我有用。

$('.FileUpGroup input[type=file]').each(function() {
    if($(this).val() === '') {
        // wabba dabba do
    }
    else {
        // badda bawwa do
    }
});