ali ali
ali ali

Reputation: 161

Javascript variable not changing inside onload function

this code always return me '3' in alert.

I select two files together (ones .mp4 format and second ones .zip format)

    function readFile(input) {
        var counter = input.files.length;
        for(x = 0; x<counter; x++){
            if (input.files && input.files[x]) {
                var extension = input.files[x].name.split('.').pop().toLowerCase();
                var reader = new FileReader();

                reader.onload = function (e) {
                    urlss = 1;
                    if(extension == 'mp4'){
                        urlss = 2;
                    }else{
                        urlss = 3;
                    }
                    alert(urlss);
                };
                reader.readAsDataURL(input.files[x]);
            }
        }
    }
<input type="file" id="files" name="files[]" accept=".png, .jpg, .jpeg, .zip, .mp4" onchange="readFile(this);" multiple />

Upvotes: 2

Views: 519

Answers (1)

Maxim Pyshko
Maxim Pyshko

Reputation: 580

That is because of var hoisting

The onload function calling after the for was ended and extension == last file extension

Try replace var with const:

function readFile(input) {
    var counter = input.files.length;
    for(let x = 0; x < counter; x++){
        if (input.files && input.files[x]) {
            const extension = input.files[x].name.split('.').pop().toLowerCase();
            const reader = new FileReader();

            reader.onload = function (e) {
                urlss = 1;
                if(extension == 'mp4'){
                    urlss = 2;
                }else{
                    urlss = 3;
                }
                alert(urlss);
            };
            reader.readAsDataURL(input.files[x]);
        }
    }
}

Update

Please check the Webber's comment below.

Upvotes: 2

Related Questions