-1

In JS and HTML I am trying to make it that when a user inputs their email address and clicks a login button the JS program will alert() the email address that they inputted. Instead, all the program does is alert the default value, value="___@gmail.com", and not the value that the user inputted. I read something about getting the default value vs. the new value, but it never quite explained. Is it that .value needs to be different?

FYI, the snippet doesn't work

function myFunction() {
 var x = document.getElementById("emailData").value;
 alert(x)
}
document.getElementById("loginButton").onclick = myFunction;
<ion-icon name="mail-outline"></ion-icon>
<input type="email" id="emailData" value="___@gmail.com" required>
<label for="">Email</label>

<button id="loginButton">Log in</button>
  • 3
    Should be `document.getElementById("loginButton").onclick = myFunction;`, your code sets the "onclick" property to the result of **calling** the function. – Pointy Mar 16 '23 at 23:01
  • Oh thanks, that fixes one of the other problems I was having. I think I'm used to having to use `()` to call a function. – printAmerigo Mar 16 '23 at 23:03
  • 2
    That is correct, but in this case you want a reference to the function instead of calling it. – Pointy Mar 16 '23 at 23:07

1 Answers1

1

After setting the event listener via .addEventListener() the snippet works

function myFunction() {
 var x = document.getElementById("emailData").value;
 alert(x)
}

document.getElementById("loginButton").addEventListener("click", myFunction);
    
Pointy
  • 405,095
  • 59
  • 585
  • 614
G.G
  • 36
  • 5