2

I have the following 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>

And the following jQuery:

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

What I want to do, is only toggle the #label if all 5 of the input:file elements pass the validation (pdf extension only). Or no file selected.

At the moment, if i select a .jpg first, the #label displays, then if i select a .pdf the #label disappears. This is incorrect as there is still a .jpg selected in one of the five input:file elements.

EDIT: Fiddle here

3 Answers 3

2

What about this?

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

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

        $('#label').toggle(ext != 'jpg');
    });
});​
Sign up to request clarification or add additional context in comments.

1 Comment

this will hide the actual label if the very last file input is OK, it needs a persistent variable to check for OK value in all fields and react accordingly
1

You would need to change it to:

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

1 Comment

Managed to do it with a variation of this answer. However @Zathrus Writer is correct, a persistent variable needs to be used. Marking this as answered because of this.
0

Managed to do it with a combination of both answers:-

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.