jennifer Jolie
jennifer Jolie

Reputation: 727

Getting image size by javascript

Why did you select an image twice the size of the second order image is not showing?

My full code: http://jsfiddle.net/ayxZM/

<script type="text/javascript">
    function handleFiles(files) {
        for (var i = 0; i < files.length; i++)
        {
            alert(files[i].size + " Bytes");
        }
    }
</script>
<input type="file" onchange="handleFiles(this.files)">​

Upvotes: 0

Views: 473

Answers (4)

LeZuse
LeZuse

Reputation: 1107

As mentioned here already: onchange does not fire when you select the same image (= don't change the value – see? that makes sense). But if you want to fire onchange everytime you can try reseting the value in onmousedown event. That way the value stays for submission and also forces onchange to fire. Demo: http://jsfiddle.net/LeZuse/ayxZM/27/
NOTE: If you need it to be touch compatible, you may wanna use ontouchstart also.

Upvotes: 0

barakadam
barakadam

Reputation: 2269

Reset your field like this. I tested it. It works perfectly.

            <script type="text/javascript">

                function handleFiles(files) {
                    for (var i = 0; i < files.length; i++)
                    {
                       alert(files[i].size + ' Bytes' );
                       reset_field('handleFilesfield');
                }
                }

                function reset_field(id) {
                $('#'+id).html($('#'+id).html());
                }

            </script>
            ​<form>
                <span id="handleFilesfield"><input type="file" onchange="handleFiles(this.files)"/></span>
            </form>

Upvotes: 0

barakadam
barakadam

Reputation: 2269

Because when you click on the same image, the second time, there is no change of file, so the onchange event does not get triggered, so the function handleFiles does not get called, so the size does not get displayed. Use another event for this case. Maybe you could reset the input file inside the handleFiles function. That way, even if the user selects the same image again, it will be considered as a new image, and therefore the onchange event will get triggered.

Upvotes: 0

nnnnnn
nnnnnn

Reputation: 150080

If you select the same image twice then the image selection hasn't really changed, so the onchange handler isn't fired. If you select a different image its size is displayed.

Upvotes: 1

Related Questions