lundi 27 juillet 2020

using eventpreventDefault getting Cannot set property 'innerHTML' of null

I'm beginner on javascript, trying to learn. Here i have simple input, where user should write something, if user writes something it will print it out and if user do not write anything it should say 'Please write something.'. in order to do that i want to use not operator (!). any idea why i get this error : Uncaught TypeError: Cannot set property 'innerHTML' of null at myFunction at HTMLFormElement.onsubmit

here is my code :

<!DOCTYPE html>
<html>

<body>

  <form onsubmit="myFunction(event)">
    <input type="text" id="text">
  </form>

 <div id="demo"></div>

  <script>
    var arvo = document.getElementById("text").value

    if (!arvo) {
      function myFunction(arvo) {
        event.preventDefault();
        document.getElementById(demo).innerHTML = "text you typed: " + arvo;

      }
    } else {
      function myFunction(arvo) {
        event.preventDefault();

        document.getElementById(demo).innerHTML = "Please write something";

      }
    }
    console.log(arvo)
  </script>

</body>

</html>

Aucun commentaire:

Enregistrer un commentaire