Uncaught TypeError: Cannot read property 'value'

Viewed 386

So I am trying to create a basic function that sets my username variable to lowercase but I keep receiving a TypeError

Error message : index.js:12 Uncaught TypeError: Cannot read property 'value' of undefined at HTMLFormElement.onSubmit (index.js:12)

If anyone could catch what I am doing wrong here I would greatly appreciate it.

const logform = document.querySelector('#logform');
var username = document.querySelector('#usernameinput');
const password = document.querySelector('#passwordinput');

logform.addEventListener('submit', onSubmit);

function onSubmit(e) { //takes in event parameter
  e.preventDefault();

  var username = username.value.toLowerCase();
  console.log(username.value);
}
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Login Portal</title>
  <link rel="stylesheet" type="text/css" href="CSS/index.css">
</head>

<body>

  <div class="loglogo">
    <!-- logo container -->
    <a href="https://www.waspc.org/" target="_blank">
      <img src="IMAGE/logo.png" alt="IMAGE">
    </a>
  </div>

  <form id="logform">

    <div class="logscreen">
      <!-- login container -->

      <label><strong>Username</strong></label>
      <!-- Username field -->
      <input autocomplete="off" id="usernameinput" type="text" name="" placeholder="Enter Username" required>

      <label><strong>Password</strong></label>
      <!-- Password field -->
      <input id="passwordinput" type="password" name="" placeholder="Enter Password" required>



      <button type="submit"><a href="home.html">Login</a></button>
      <!-- Login button -->
      <button class="newbutton" type="button"><a href="newuser.html">New User</a></button>
      <!-- New User button -->
      <button type="reset">Cancel</button>
      <!-- Cancel button -->

    </div>

  </form>

  <script src="JS/index.js"></script>
</body>

</html>

1 Answers

I think this may be a naming conflict with username. See below:

const elUsernameInput = document.querySelector('#usernameinput');
const elPasswordInput = document.querySelector('#passwordinput');

logform.addEventListener('submit', onSubmit);

function onSubmit(e) { //takes in event parameter
    e.preventDefault();

    const username = elUsernameInput.value.toLowerCase();
    console.log(username.value);
}

If this doesn't work:

  • Make sure your script is included after the input fields and form fields in the HTML.
  • Make sure logform is set somewhere. You may need another lookup, like const elLogForm = document.querySelector('#logform').
  • Make sure the ids you've specified in the script are present on the correct elements.
Related