0

I have a function in JS to preview images in filupload control:

<script type="text/javascript">
      function readURL(input) {
          if (input.files && input.files[0]) {
              var reader = new FileReader();
              reader.onload = function (e) {
                  var uplImg = document.getElementById('preImg');
                  uplImg.setAttribute('src', e.target.result);
              }
           reader.readAsDataURL(input.files[0]);
           }
       }
       var fu = document.getElementById("fuImagenCliente");
       fu.onchange(function() {
               readURL(this);
       })
</script>   

Chrome and Firefox don´t catch the error and "works fine" but in javascript console I see error:

Cannot read property 'onchange' of null (Chrome)
Uncaught TypeError: Cannot read property 'onchange' of null (Firefox)

However IE 11 yes he does:
Error IE11
The function that is executed in the event onchange expect a parameter but I do not know what parameter to pass to this, just need this parameter.

Information
When I debug, I see that the ClientClient control is not loaded, I am working in ASP.Net and surely the function is trying to find a control which has not yet been loaded.

Pabli770
  • 131
  • 1
  • 8
  • 1
    Without looking too deeply, make sure your JavaScript is firing after the DOM has loaded. `document.addEventListener('DOMContentLoaded', function(){ document.getElementById('fuImagenCliente').onchange = changeEventHandler })` – BotNet Jun 13 '18 at 15:09
  • I´m working in ASP.Net and I still find javascript difficult. I think that JavaScript is not loaded because the script is executed before receiving the reply from the server. Can I force load Javascript in some way? – Pabli770 Jun 13 '18 at 15:29
  • Depending on implementation, you can *defer* or call it asynchronously after the data is retrieved. You'd have to post more about your code to get to the heart of your issue. This is an X/Y problem – BotNet Jun 13 '18 at 16:01
  • You need the HTML code? – Pabli770 Jun 13 '18 at 16:06
  • Well, in order to determine order of operation, you would need to see something more complete, which often includes other JavaScript and HTML. If the content is loaded dynamically (e.g., via iFrame or AJAX) then yes, there is no element on the page with that ID, even when the DOM has been loaded. – BotNet Jun 13 '18 at 17:37
  • I resolve this removing this code ``var fu = document.getElementById("fuImagenCliente"); fu.onchange(function() readURL(this); })`` – Pabli770 Jun 14 '18 at 12:44
  • So your solution was to remove functionality? Functionality you expected everyone here to somehow know you didn't need? – BotNet Jun 14 '18 at 18:43

0 Answers0