Uncaught TypeError: Can not read property 'value' of null

1

What is happening?

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <script type="text/javascript" src="asignar.js"></script>
    <title>Asignar</title>
</head>
<body>

    <p>Est es el número original: </p><input type="number" id="original">
    <p>Est es el número modificado: </p><input type="number" id="modificado">

</body>
</html>

And the content of assign.js is:

var numero = 7;

document.getElementById("original").value=numero;

mod(numero);

document.getElementById("modificado").value=numero;

function mod(a){
    a=8;
}
  

ERROR: document.getElementById ("original"). value = number;

    
asked by giomaretti 13.09.2016 в 22:20
source

3 answers

4

It's because you're loading the javascript file before the DOM has loaded completely. What you could do is add an event that listens when the DOM has been loaded and execute your code.

You could do this:

   document.addEventListener("DOMContentLoaded", function(event) {
      var numero = 7;
      document.getElementById("original").value=numero;
      mod(numero);
      document.getElementById("modificado").value=numero;
      function mod(a){
        a=8;
      }
    }
    
answered by 13.09.2016 в 22:51
3

You are loading the JavaScript code before the <input> exists in the DOM, you can pass the .js file to the end of the file (of the body, more precisely):

<body>
  <input type="number" id="original">
  <input type="number" id="modificado">

  <script src="asignar.js"></script>
</body>
    
answered by 13.09.2016 в 22:25
0

Another possible solution would be to add defer to the loading of your script.

<script defer type="text/javascript" src="asignar.js"></script>
    
answered by 26.12.2017 в 22:36