I have a welcome page that collects the user input and I want this information to be shown on other pages as this is a basic jQuery game for a college assessment.
I have tried different ways but I either get undefined appear where I want the userName to be shown, or nothing shows at all, I would preferably like this to show when the page loads on page load.
Any help or suggestions would be greatly appreciated.
// let setAvatar = document.getElementById('userAvatar'); //Stores chosen avatar picture for later use
const avatarPics = ["avatar1.png", "avatar2.png", "avatar3.png", "avatar4.png"]; // Array to store avatar images for avatar generator
let randomPic; // This variable will store the index value of the random avatar image in the array for later use
let score = 0;
let userName;
let welcomeUser;
$(document).ready(function() {
// $('validateInput').validate();
$('#submit').on('click', setStorage)
userName = document.getElementById('userName').value;
if (userName === '') {
$('.error-message').show();
} else {
window.location.href = 'avatar.html';
}
function setStorage() {
let userVal = $('#userName').val();
localStorage.setItem('userVal', userVal);
}
window.onload = function() {
let getName = localStorage.getItem('userVal');
$('#welcomeUser').html(getName);
}
// function welcomeUser(){
// let welcomeUserName = $('#userName').val();
// $('#welcomeUser').text('Hi ' + welcomeUserName);
// }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="card bg-transparent border-0" style="width: 25rem; height: 25rem; margin-left: 18%; margin-top: 10%;">
<div class="card-body text-center d-flex flex-column align-items-center">
<div class="display-6 mb-2" id="welcomeUser"></div>
<h1 class="card-title display-6 mb-3 mt-5" id="welcomeUser">Choose Your Avatar</h1>
<div id="avatar"></div>
<div>
<button class="btn btn-lg btn-primary me-5" type="button" id="button-addon2 genBtn">Generate Avatar</button>
<button class="btn btn-lg btn-primary" type="button" id="button-addon2 setBtn">Set Avatar</button>
</div>
</div>
</div>
Thanks to Rory, I managed to research and understand exactly what I was doing wrong, in order to pass the user input to another page, I had t have a separate .js file to gather and store this information with localStorage. Thanks again Rory