jQuery验证多个输入:文件

时间:2012-10-05 14:09:32

标签: jquery html

我有以下HTML:

<input id="upload1" type="file" /><br/>
<input id="upload2" type="file" /><br/>
<input id="upload3" type="file" /><br/>
<input id="upload4" type="file" /><br/>
<input id="upload5" type="file" /><br/>
<span id="label" style="color:red; display:none">
Wrong filetype!
</span>

以下jQuery:

$('input:file').change(function(){
    var ext = $(this).val().split('.').pop().toLowerCase();
    $('#label').toggle(ext != 'pdf');
});

我想要做的是,如果所有5个#label元素都通过验证(仅限pdf扩展名),则只切换input:file。或者没有选择文件。

目前,如果我先选择.jpg,则会显示#label,如果我选择.pdf,则#label会消失。这是不正确的,因为在五个.jpg元素之一中仍然选择了input:file

编辑:小提琴here

3 个答案:

答案 0 :(得分:2)

这个怎么样?

$('input:file').change(function(){

    $('input:file').each(function(){
      var ext =   $(this).split('.').pop().toLowerCase();

        $('#label').toggle(ext != 'jpg');
    });
});​

答案 1 :(得分:1)

您需要将其更改为:

$('input:file').change(function(){
    var
        all_ok = true,
        inputs_set = $('input:file');

    for (var e in inputs_set) {
        if (e.val().split('.').pop().toLowerCase() != 'pdf') {
            all_ok = false;
        }
    }

    $('#label').toggle(!all_ok);
});

答案 2 :(得分:0)

使用两个答案的组合来管理: -

$('input:file').change(function() {  
    var allok = true;
    $('input:file').each(function() {
        if ($(this).val() !== "" &&
            $(this).val().split('.').pop().toLowerCase() != 'pdf') {
                allok = false;
        }
    });
    $('#label').toggle(!allok);
});