2012-10-05 139 views
2

我有以下HTML:jQuery的验证多个输入:文件

<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'); 
}); 

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

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

编辑:小提琴here

回答

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); 
}); 
+0

管理这个答案的变化来做到这一点。不过@Zathrus Writer是正确的,需要使用一个持久变量。标记这是因为这个答案。 –

2
这个

什么?

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

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

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

如果最后一个文件输入正常,它将隐藏实际标签,它需要一个持久变量来检查** all **字段中的OK值并作出相应的反应 –

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); 
});