0

When i print out txtDisplayname in the JS file, it gives me null. Can anyone help?

I want to print txtDisplayname when either the Login or Sign up buttons are pressed, but instead of registering the input, it gives off a null value

firebase.auth().onAuthStateChanged(firebaseUser => {
  if (firebaseUser) {
    const Displayname = document.getElementById('txtDisplayname');
    console.log(Displayname);
    welcomeBackText.innerHTML = "Welcome back " + Displayname;
    btnLogout2.addEventListener('click', e => {
      firebase.auth().signOut();
    });
  }
  else {
    location.href = './login/loginPage.html'
  }
})
<div class="container">
<input type="email" id="txtEmail"  placeholder="Email" >
<hr>
<input type="password" id="txtPassword"  placeholder="Password" >
<hr>
<input type="text" id="txtDisplayname"  placeholder="Display Name" >
<br>
<button id="btnLogin" class="btn btn-action">Log In</button>

<button id="btnSignUp" class="btn btn-secondary">Sign up</button>

<button id="btnLogout" class="btn btn-action hide">Log Out</button>

</div>
BeerusDev
  • 1,444
  • 2
  • 11
  • 30
  • Displayname is a DOM element, not sure why you would be using it as a string – epascarello Jun 24 '21 at 16:41
  • `Displayname.value` might give you what you need? – evolutionxbox Jun 24 '21 at 16:41
  • https://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element – epascarello Jun 24 '21 at 16:42
  • Does this answer your question? [Why does jQuery or a DOM method such as getElementById not find the element?](https://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element) – Heretic Monkey Jun 24 '21 at 16:45

1 Answers1

0
  • The element probably hasn't been loaded when you tried selecting it. Wait for DOMContentLoaded, then try selecting it.

  • You have to retrieve the value of the input. Use Displayname.value

Try this:

document.addEventListener("DOMContentLoaded", function() {
  if (firebaseUser) {
    const Displayname = document.getElementById('txtDisplayname');
    console.log(Displayname);
    welcomeBackText.innerHTML = "Welcome back " + Displayname.value;
    btnLogout2.addEventListener('click', e => {
      firebase.auth().signOut();
    });
  } else {
    location.href = './login/loginPage.html'
  }
})
Spectric
  • 30,714
  • 6
  • 20
  • 43