Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Norbertho's avatar

why onchange event gets fired

Hi, I have livewire component with a file input. I using Alpine.js on this compnent and I would like to get the selected file filesize as soon as a user select a file. I dont know why but without selecting any file as soon as the page loads i have the following error:

alpine.js:1873 Uncaught TypeError: Cannot read property 'size' of undefined

Althoug this code works fine , as i select a file it echo out the filesize but i dont know why it is fireing on page load as well of course on page load i dont have any file selected yet so that is why i geting the error above. How could i prevent running the showFileSize() on pageload?

My code:

<div>
    <div x-data
    x-init="
    document.getElementById('fileinput').onchange = function showFileSize() {
    
        var input = document.getElementById('fileinput');
            var file = input.files[0];
            addPara(file.size);
    };
    
    function addPara(text) {
        var p = document.createElement('p');
        p.textContent = text;
        document.body.appendChild(p);
    }
    ">

        <input type='file' id='fileinput'>

    </div>
</div>
0 likes
1 reply
Nakov's avatar
Nakov
Best Answer
Level 73

@norbertho you can simplify it, and add the change event on the input itself.

I tried this one and it worked:

<div x-data>

<input type='file' x-ref="file" @change="
    fileSize = $refs.file.files[0].size
    let p = document.createElement('p');
    p.textContent = fileSize;
    document.body.appendChild(p);
" id='fileinput'>

</div>
1 like

Please or to participate in this conversation.