How to call a javascript function

2

I have the following function.

function readURL(input) {
   if (input.files && input.files[0]) {
      var reader = new FileReader();
      reader.onload = function (e) {
         $('#preview').attr('src', e.target.result);
      };
      reader.readAsDataURL(input.files[0]);
   }
}

And I want to be able to call it with the id file, but leaving it ready so that if I want to use it again with the id file_2, I can do it. I'm very green in this. I started with this:

$('#file').change(function () {
   $(this).
});

But in the $(this). I stay blocked. Does someone help me?

    
asked by Dario B. 29.08.2018 в 09:00
source

1 answer

2

In your jquery selector for .change you should include both ids. Then for how do you have your readURL function you should just pass this to your function, since this is the input itself within .change .

function readURL(input) {
  if (input.files && input.files[0]) {
      console.log(input.files[0]);
      var reader = new FileReader();

      reader.onload = function (e) {
          $('#preview')
              .attr('src', e.target.result);
      };

      reader.readAsDataURL(input.files[0]);
  }
}

$(document).ready(function() {
  $('#file, #file_2').change(function () {
      readURL(this);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <input type="file" id="file" />
  <input type="file" id="file_2" />
</form>
    
answered by 29.08.2018 / 09:25
source