skip to Main Content

I have this simple script that works great to avoid uploading large files.

I need it to work with Name or class because it won’t work with ID document.getElementById("video573623_upload_field"); because the ID is dynamic, it’s a WordPress theme.

<input type="file" name="files[]" id="video573623_upload_field" class="custom-file-input" multiple="">

<script>

var uploadField = document.getElementById("video573623_upload_field");

uploadField.onchange = function() {
    if(this.files[0].size > 10000){
       alert("File is too big!");
       this.value = "";
    };
};

</script>

2

Answers


  1. Try var uploadField = document.getElementsByClassName('custom-file-input')[0];
    Previously when you were using getElementByClassName it was returning a reference variable of array, and then you were directly using onChange() on that reference array, maybe that’s why it was not working.

    getElementById() directly returns the element because id is always unique.

    Login or Signup to reply.
  2. If you can’t use class name or anything by default in the input, you can add a custom attribute the custom attributes have to start whit "data" example

    <input data-customfile="custom-upload" />
    

    Use document.getAttribute('data-files')

    To get the element also you can get the value of the attribute if you needed, you can see more info here

    https://developer.mozilla.org/en-US/docs/Web/API/Element/getAttribute

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search