Reputation:
Hello I made a "login screen" that when you enter a name you will be transfer to another html file. I made a welcome back screen that says Welcome back, "username". But for some reason the variable that I use to take the value of the username field is undefined. This is the login screen html code:
<form id="login-form" metod="post" action="main.html">
<div class="txt_field">
<input id="username" type="text" required>
<label>username</label>
</div>
<input onclick="validate()" type="submit" id="submit" value="Login">
</form>
</div>
<script type="text/javascript" src="functions.js"></script>
-> this is the js file:
let username1;
function validate(){
username1=document.getElementById(username).value;
}
document.getElementById('show_username').innerHTML = username1;
-this is the after login html file
<center>
<h1>Welcome back,<br>
<span id="show_username"></span>
</h1>
</center>
<script type="text/javascript" src="functions.js"></script>
**ofc I didn't include all the code for basic reasons.
Upvotes: 0
Views: 190
Reputation: 334
Here is what happens in JavaScript when you load your page:
// username1 is set to null
let username1;
// validate() function is created
function validate(){
username1=document.getElementById(username).value;
}
// show_username element is populated with username1 (still null)
document.getElementById('show_username').innerHTML = username1;
When you call the validate function, username1
is updated but document.getElementById('show_username')
is not.
You also are referencing a username
variable instead of 'username'
as a string.
Your code will work if you move line 5 into the validate
function, and fix that issue.
let username1;
function validate(){
username1=document.getElementById('username').value;
document.getElementById('show_username').innerHTML = username1;
}
Upvotes: 2