Tibi Buzdugan
Tibi Buzdugan

Reputation: 82

How can I get the content of a file input with pure javascript?

I modified a file input button (basically it is hidden and something else is rendered on top of it), and I want to get the 'meta' content of it after one or more files are uploaded - in the default input file button, there is a text that gives the user information about the submitted files (one file uploaded/ 10 files uploaded, and so on, depending on the browser).

I did this via jQuery, with the code below, but unfortunately I can not use jQuery on the website because there is another js library that influences many plugins and behaviours (masonry).

<script>
$("#upload-form-file-button").change(function () {
var fileName = $(this).val().replace('C:\\fakepath\\', '');
if (this.files.length == 1)
    $("#upload-info").text(this.files.length + " image selected");
else
    $("#upload-info").text(this.files.length + " images selected");
});
</script>

How can I do this in pure javascript, so that I don't have to change the js library?

Thank you. Tibi

Upvotes: 0

Views: 3814

Answers (1)

jperezov
jperezov

Reputation: 3171

Translated your jQuery to vanilla JS:

document.getElementById("upload-form-file-button").onchange = function () {
  var fileName = this.value.replace('C:\\fakepath\\', '');
  var uploadInfo = document.getElementById('upload-info');
  if (this.files.length == 1)
    uploadInfo.innerText = this.files.length + " image selected";
  else
    uploadInfo.innerText = this.files.length + " images selected";
};

Additionally, if you have a conflict with jQuery's $ variable, you can always load jQuery with noConflict.

Upvotes: 1

Related Questions