How to design a custom file upload button such that the label changes when file is uploaded

Viewed 450
<form method="post" enctype="multipart/form-data" action="">
  <span id="filename">Select your file</span>
    <label for="file-upload">Browse<input type="file" id="file-upload"></label>
</form>
<script>
$('#file-upload').change(function() 
    var filepath = this.value;
    var m = filepath.match(/([^\/\\]+)$/);
    var filename = m[1];
    $('#filename').text(filename);
});
</script>

I just wanted help to implement the submit button such that each would not utilize the separate filename id that we are using here. I am new to js and have many file upload button in my project and when I am using classes every file name change is being reflected only on one button.

1 Answers

Very quickly cobbled together using vanilla Javascript ~ essentially if there are multiple file input elements and you want the same functionality for each then you would want to obtain a reference to the nodelist collection ( querySelectorAll will return a nodelist ) and, for each one, assign a change event handler. Using a combination of parentNode and previousElementSibling you can identify the span element and modify it quite easily.

The actual uploading of the file could be handled by the change handler and modifications to the DOM done as a result of this.

    document.querySelectorAll('input[type="file"]').forEach( input=>{
        input.addEventListener('change',function(e){
            this.parentNode.previousElementSibling.textContent=this.value.match(/([^\/\\]+)$/)[1];
            this.parentNode.textContent='Uploading...';
        });
    });
<form method='post' enctype='multipart/form-data'>
    <span>Select your file</span>
    <label for='file-upload'>Browse<input type='file' /></label>
</form>

<form method='post' enctype='multipart/form-data'>
    <span>Select your file</span>
    <label for='file-upload'>Browse<input type='file' /></label>
</form>

Related