javascripthtmlnullgetelementbyid

Null error by document.getElementById on HTML


<body>
  <script lang="javascript">
    function myFunction() {
      var name = "";
      var password = "";
      name = document.getElementById('name');
      password = document.getElementById('password');
      alert(name)
      alert(password)
    }
  </script>
  <h1 id="Center">Log in</h1>
  <input type="text" id="Center" id="name" style="background-color: rgb(255, 255, 255); border-radius: 0px;">
  <input type="text" id="Center" id="password" style="background-color: rgb(255, 255, 255); border-radius: 0px;">
  <input type="button" id="Center" style="width: 170px;" onclick="myFunction()" value="Submit">
</body>

I want to make the input text to alert and I get data of text using a document.getElementById and there has two texts and one button and id center is the code that the object can go to the center place on the screen.

I tried to make it string or write one more time and there has no ways to be good.


Solution

  • Try like this:

    <!DOCTYPE html>
    <html>
    
    <head>
      <style>
        #Center {
          display: block;
          margin: auto;
        }
      </style>
    </head>
    
    <body>
      <script lang="javascript">
        function myFunction() {
          var name = "";
          var password = "";
          name = document.getElementById('name').value;
          password = document.getElementById('password').value;
          alert("Name: " + name + "\nPassword: " + password);
        }
      </script>
    
      <h1 id="Center">Log in</h1>
      <input type="text" id="name" style="background-color: rgb(255, 255, 255); border-radius: 0px;" placeholder="Enter your name">
      <input type="password" id="password" style="background-color: rgb(255, 255, 255); border-radius: 0px;" placeholder="Enter your password">
      <input type="button" id="Center" style="width: 170px;" onclick="myFunction()" value="Submit">
    </body>
    
    </html>