Displaying form input on another html page - javascript

I am new to javascript and DOM manipulation. So I have this form I have created basically to get names of players. What I want to achieve is to get the player names and display them on the games page once they are redirected after clicking on the button. It does not display the line of code and returns an error:
(VM4444:1 Uncaught ReferenceError: player1 is not defined at
:1:1).
function next() {
var player1 = document.getElementById('play1').value;
var player2 = document.getElementById('play2').value;
if (player1 === '' || player2 === '') {
document.getElementById("error").style.color = "red";
document.getElementById("error").innerHTML = "Please enter both names";
} else {
location.href = "game.html";
}
document.getElementById('name1').innerHTML = player1.value;
document.getElementById('name2').innerHTML = player2.value;
console.log(player1, player2);
}
<div class="col-lg-4 col-md-4 col-sm-12 form">
<form>
<small class="form-text text-muted">We'll never share your details with anyone else.</small>
<div class="form-group">
<label for="player1">Player 1</label>
<input type="text" class="form-control" id="play1" aria-describedby="play1help">
</div>
<div class="form-group">
<label for="player1">Player 2</label>
<input type="text" class="form-control" id="play2" aria-describedby="play1help">
</div>
</form>
<button class="btn btn-lg btn-primary btn-block mt-3" onclick="next();">Start</button>
</div>

Using localStorage you can easily achieve this,
localStorage["key"] = value;
In next page you can get the value by using
value = localStorage["key"];
First Page
function next() {
var player1 = document.getElementById('play1').value;
var player2 = document.getElementById('play2').value;
if (player1 === '' || player2 === '') {
document.getElementById("error").style.color = "red";
document.getElementById("error").innerHTML = "Please enter both names";
} else {
location.href = "game.html";
}
document.getElementById('name1').innerHTML = player1.value;
document.getElementById('name2').innerHTML = player2.value;
localStorage["player1"] = player1;
localStorage["player2"] = player2;
console.log(player1, player2);
}
Next Page
function getPlayer() {
player1 = localStorage["player1"];
player2 = localStorage["player2"];
console.log(player1,player2)
}

Related

(Login page) How to check if a username and a password typed in by the user match with the ones saved in two arrays, using JS?

I am a JavaScript (and an overall programming) newbie, and this is one of my first exercices. I have to do a login page, where the user has to type in an already existing username and password, which are saved in two different arrays (one for the usernames and one for the passwords):
const users=["java", "visual", "personal", "key", "master"]
const passwords=["script", "studio", "computer", "board", "chief"];
Once the user clicks a "submit" button, the website tells him if the login was successful or not (if the credentials typed in exist or not).
The problem is that when the button is clicked, nothing happens: in the code, it should check if the credentials typed in by the user match with the existing ones in the arrays AND with their positions, but it doesn't, and I don't understand why.
The code is pasted below.
JS function:
function login(){
const a=document.getElementById("usn").value;
const b=document.getElementById("psw").value;
for(var i=0; i<users.length; i++){
for(var j=0; j<passwords.length; i++){
if(users.indexOf(a)==passwords.indexOf(b)){
if(users[i].includes(a) && passwords[j].includes(b)){
var suc=document.getElementById("success");
suc.innerHTML="Login successful";
suc.style.backgroundColor="green";
}
else{
var fail=document.getElementById("fail");
fail.innerHTML="Login failed, user not registered";
fail.style.backgroundColor="red";
}
}
else
continue;
}
}
}
HTML (if needed):
<div class="col-md-5 col-sm-6 col-12">
<p class="font title pt-3">Login</p>
<p class="font">Don't have an account yet? <span>Create yours now</span>, it takes just a few seconds.</p>
<div id="fail" class="pt-2 pb-2 ps-1 pe-1 font"></div>
<div id="success" class="pt-2 pb-2 ps-1 pe-1 font"></div>
<br>
<div>
<p class="font">Username</p>
<div>
<input type="text" class="inf pb-3 inf" id="usn" onclick="switchColors()">
</div>
</div>
<br>
<div>
<p class="font">Password</p>
<div>
<input type="text" class="inf pb-3 inf" id="psw" onclick="switchColors()">
<i class="bi bi-eye-slash" id="eye2" onclick="change()"></i>
<i class="bi bi-eye hidden" id="eye1" onclick="change()"></i>
</div>
</div>
<br>
<button type="button" class="btn btn-primary" id="btn" onclick="login()">Login</button>
</div>
</div>
CSS (if needed):
.inf{
border: none;
outline: none;
border-bottom: 1px solid black;
}
.hidden{
display: none;
}
Note: this is an exercise for school to be made ONLY for learning purposes.
Maybe like This:
const users=["java", "visual", "personal", "key", "master"]
const passwords=["script", "studio", "computer", "board", "chief"];
function login(){
const a=document.getElementById('usn').value;
const b=document.getElementById('psw').value;
var inxa = users.indexOf(a);
var inxb = passwords.indexOf(b);
if(inxa < 0){
console.log('Login not found...');
}else if(inxb < 0 || inxa !== inxb){
console.log('Password incorrect...');
}else{ /* (inxa > 0 && inxb > 0 && inxa === inxb) */
console.log('You have successfully logged in');
}
}
<div>Login:</div>
<input type="text" id="usn">
<div>Password:</div>
<input type="text" id="psw">
<br>
<button type="button" onclick="login()">Login</button>
There are so many ways to become the same result. Because you are leaning JS, this is another approach. I'll leave the rest of the code to you for learning ;-)
Note that (passwords[i] == psw) will return true or false
const usn = document.getElementById("usn").value;
const psw = document.getElementById("psw").value;
let success = false;
for (let i=0; i < users.length; i++) {
if (users[i] == usn) {
success = (passwords[i] == psw);
}
}
if (success) {
// login success
} else {
// login failed
}
const users = ["java", "visual", "personal", "key", "master"];
const passwords = ["script", "studio", "computer", "board", "chief"];
function login() {
const username = document.getElementById("usn").value;
const password = document.getElementById("psw").value;
const indexUsername = users.indexOf(username);
const indexPassword = passwords.indexOf(password);
if(indexUsername < 0){
console.log("user not found")
} else if (indexUsername === indexPassword) {
const success = document.getElementById("success");
success.innerHTML = "Login successful";
success.style.backgroundColor = "green";
} else {
const fail = document.getElementById("fail");
fail.innerHTML = "Login failed, user not registered";
fail.style.backgroundColor = "red";
}
}
Note: always try to use explicit names in your variables, functions, etc.

JavaScript code wont execute but get printed as part of html

I have this html code with js inside and every time i submit the js wont execute but get printed as html, saw many similar problems on stack overflow they said something about not closing <div> correctly but i cant find the error on my code
This is my html code:
<div class="container-fluid">
<div class="row" id="riparues_frm">
<form method="post" action="ruajRiparues.php" id="FormaRuaj_rp" enctype="multipart/form-data">
<input type="hidden" name="idRiparues" id="idRiparues" />
<div class="form-group row d-flex" style="margin-bottom: 20px;" >
<div class="col-sm-4">
<input type="button" class="btn btn-outline-info" value="Kerko skript sipas pershkrimit" onclick="lookUpBox({
title: 'Kerko skript sipas pershkrimit',
url: 'kerkoSkript_sipas_emrit.php?chars=',
onItemSelected: function(data){
$('input[id=' +
'idRiparues]').val(data.idRiparues);
$('#delref').attr('href','fshi_riparues.php?id=' + data.idRiparues);
$('input[name=kodi]').val(data.kodi);
$('input[name=seq]').val(data.sequenca);
$('input[name=pershkrimi]').val(data.pershkrimi);
$('#scripti').val(data.script);
$('#scripti').load(data.script, resizeArea);
$('#modelScripti').val(data.modelScript);
$('#modelScripti').load(data.modelScript, resizeArea);
$('#dataregj').val(data.datazgjedh);
$('#tipi').val(data.Tipi);
//kosta070622 start
var checkTipi = data.Tipi;
**filter()**
//kosta070622 end
},
tableHeader: ['idRiparues','kodi', 'pershkrimi','sequenca','script','modelScript','data']
})
" />&nbsp
</div>
and this is my js code:
<script>
function filter() {
if(isadmin === 1){
if(checkTipi != 'S' && checkTipi != 'B'){
document.getElementById('modelScripti').hidden = true;
document.getElementById('pathi').hidden = false;
document.getElementById('myfile').hidden = false;
document.getElementById('seq').disabled = true;
document.getElementById('lblpershkrimi').innerHTML = 'Emri Skedarit';
document.getElementById('lblscript').innerHTML = 'Pathi Relativ';
document.getElementById('lblmodelscript').innerHTML = 'Model Pathi Relativ';
$('#pathi').val(data.modelScript);
}else{
document.getElementById('modelScripti').hidden = false;
document.getElementById('pathi').hidden = true;
document.getElementById('myfile').hidden = true;
document.getElementById('seq').disabled = false;
document.getElementById('lblpershkrimi').innerHTML = 'Pershkrimi';
document.getElementById('lblscript').innerHTML = 'Script';
document.getElementById('lblmodelscript').innerHTML = 'Model Script';
}
}else{
if(checkTipi != 'S' && checkTipi != 'B'){
document.getElementById('modelScripti').hidden = true;
document.getElementById('pathi').hidden = false;
document.getElementById('myfile').hidden = true;
document.getElementById('seq').disabled = true;
document.getElementById('pathi').disabled = true;
document.getElementById('scripti').disabled = true;
document.getElementById('Edito').disabled = true;
document.getElementById('lblpershkrimi').innerHTML = 'Emri Skedarit';
document.getElementById('lblscript').innerHTML = 'Pathi Relativ';
document.getElementById('lblmodelscript').innerHTML = 'Model Pathi Relativ';
$('#pathi').val(data.modelScript);
}else{
document.getElementById('modelScripti').hidden = false;
document.getElementById('pathi').hidden = true;
document.getElementById('myfile').hidden = true;
document.getElementById('seq').disabled = false;
document.getElementById('scripti').disabled = false;
document.getElementById('Edito').disabled = false;
document.getElementById('lblpershkrimi').innerHTML = 'Pershkrimi';
document.getElementById('lblscript').innerHTML = 'Script';
document.getElementById('lblmodelscript').innerHTML = 'Model Script';
}
}
console.log(Boolean(isadmin));
console.log("HYRI KETU");
}
</script>
The html code it was written by someone else i just added the function filter and thats the the code that is being printed as html on the website.
I think that you are missing 3 div closing tags, and that is why your script is being read as html.
//1<div class="container-fluid">
//2<div class="row" id="riparues_frm">
<form method="post" action="ruajRiparues.php" id="FormaRuaj_rp" enctype="multipart/form-data">
<input type="hidden" name="idRiparues" id="idRiparues" />
//3 <div class="form-group row d-flex" style="margin-bottom: 20px;" >
//4 <div class="col-sm-4">
<input type="button" class="btn btn-outline-info" value="Kerko skript sipas pershkrimit" onclick="lookUpBox({
title: 'Kerko skript sipas pershkrimit',
url: 'kerkoSkript_sipas_emrit.php?chars=',
onItemSelected: function(data){
$('input[id=' +
'idRiparues]').val(data.idRiparues);
$('#delref').attr('href','fshi_riparues.php?id=' + data.idRiparues);
$('input[name=kodi]').val(data.kodi);
$('input[name=seq]').val(data.sequenca);
$('input[name=pershkrimi]').val(data.pershkrimi);
$('#scripti').val(data.script);
$('#scripti').load(data.script, resizeArea);
$('#modelScripti').val(data.modelScript);
$('#modelScripti').load(data.modelScript, resizeArea);
$('#dataregj').val(data.datazgjedh);
$('#tipi').val(data.Tipi);
//kosta070622 start
var checkTipi = data.Tipi;
filter()
//kosta070622 end
},
tableHeader: ['idRiparues','kodi', 'pershkrimi','sequenca','script','modelScript','data']
})
" />&nbsp
//1 </div>
//2 </div> //this and below are added by me
//3</form>
//4 </div>
//5 </div>

Swap image with JavaScript

I made a small script for when someone clicks on this eye image the input type was changed from ''password'' to ''text''
function mostrarocultarsenha() {
var senha = document.getElementById("senha")
if (senha.type == "password") {
senha.type = "text";
} else {
senha.type = "password"
}
}
<div class="campo">
<label for="password"><strong>Senha</strong></label>
<input type="password" name="senha" id="senha" required></input>
</div>
<img class="olho" id="olho" src="https://via.placeholder.com/100" onclick="mostrarocultarsenha()">
Photo from my website
I want that when the input changes from password to text, the image also changes from an eye to an eye with a scratch, and then if clicked again, go back to normal eye, does anyone know how I can do this?
const olho = document.querySelector("#olho")
if (senha.type === "password") {
senha.setAttribute("type", "text")
olho.src = "image link/path"
} else {
senha.setAttribute("type", "password")
olho.src = "another image link/path"
}
w3schools
basically it's just a element ID src it's actually really simple
<div class="campo">
<label for="password"><strong>Senha</strong></label>
<input type="password" name="senha" id="senha" required></input>
</div>
<a onclick="mostrarocultarsenha()"><img class="olho" id="olho" src="assets/closedEye.png"/></a>
function mostrarocultarsenha() {
var senha = document.getElementById("senha")
if (senha.type == "password") {
senha.type = "text";
document.getElementById("olho").src = "assets/openedEye.png";
} else {
senha.type = "password"
document.getElementById("olho").src = "assets/closedEye.png";
}
}

Custom event logging multiples

I wrote a custom Javascript event to handle if username exists among the list of users. when there is no user match, it logs fine that there is no user with that name. but the problem is when there is a user match, both if and else runs simultaneously. the code works like this: user types his username, and as soon as the password field is clicked, an event is fired to check if username exists or not. I am new to Javascript am just trying to figure out custom event thanks.
Below is my code:
var user_list = [
{
username:"john",
name:"john.doe",
last_seen:"2mins ago"
},
{
username:"mary",
name:"Mary marta",
last_seen:"2hrs ago"
},
{
username:"susan",
name:"susy457",
last_seen:"45mins ago"
},
{
username:"moses",
name:"moe23",
last_seen:"45mins ago"
},
];
var password = document.getElementById("passwordtext");
password.addEventListener('click', checkPassword);
//Custom event to grab username field when the user is about to type the password
var users = document.getElementById('usertext');
users.addEventListener('trigger', function(e){
var display = e.target.value;//e.target.value
if(display === ""){
//console.log('empty string..');
}else{
for(var i = 0; i < user_list.length; i++){
if(user_list[i].username === display){
console.log('user found..')
}
else{
console.log('user not found!');
}
};
};
event.preventDefault();
});
function checkUser(){
var event = new CustomEvent('trigger');
users.dispatchEvent(event);
};
function checkPassword(e){
checkUser()
passcode = e.target.value;
//console.log(e.target.value);
event.preventDefault();
};
edit: here is my html form code
<form>
<div class="form-row">
<div class="col">
<input type="text" name="usertext" id ="usertext" class="form-control"placeholder="Email or username"/>
</div>
<div class="col">
<input type="password" id ="passwordtext" class="form-control" placeholder="password"/>
</div>
<div class="col-auto">
<a class="btn btn-primary" id="id-login" href="#" role="button">login</a>
</div>
</div>
</form>
Get your check outside of the for loop. See this example.
However there are even easier ways to do it when you just search your Javascript object for the existence of a user instead of looping the object.
var user_list = [{
username: "john",
name: "john.doe",
last_seen: "2mins ago"
},
{
username: "mary",
name: "Mary marta",
last_seen: "2hrs ago"
},
{
username: "susan",
name: "susy457",
last_seen: "45mins ago"
},
{
username: "moses",
name: "moe23",
last_seen: "45mins ago"
},
];
var password = document.getElementById("passwordtext");
password.addEventListener('click', checkPassword);
//Custom event to grab username field when the user is about to type the password
var users = document.getElementById('usertext');
users.addEventListener('trigger', function(e) {
var display = e.target.value; //e.target.value
if (display === "") {
//console.log('empty string..');
} else {
var userFound = false;
for (var i = 0; i < user_list.length; i++) {
if (user_list[i].username === display) {
userFound = true;
break;
}
};
if (userFound) {
console.log('user found!');
} else {
console.log('user not found!');
}
};
event.preventDefault();
});
function checkUser() {
var event = new CustomEvent('trigger');
users.dispatchEvent(event);
};
function checkPassword(e) {
checkUser()
passcode = e.target.value;
//console.log(e.target.value);
event.preventDefault();
};
<form>
<div class="form-row">
<div class="col">
<input type="text" name="usertext" id="usertext" class="form-control" placeholder="Email or username" />
</div>
<div class="col">
<input type="password" id="passwordtext" class="form-control" placeholder="password" />
</div>
<div class="col-auto">
<a class="btn btn-primary" id="id-login" href="#" role="button">login</a>
</div>
</div>
</form>

Two parameters on a function

I'm trying to make a button onclick event jump to another function if input fields is empty. The function inside the if-statement should have two parameter(one array, one string variable). The function is looping trough all input elements and check if they have a value, if not then add text to a variable that later on is assign to a p-element with .innerHTML.
It worked with only the input parameter, but when I tried to add msg, it stopped working. Maybe it's a simple reason, but I am new to this.
How can I make this work?
var assignment = document.getElementById("assignment");
var inputs = assignment.getElementsByTagName('input');
var btnCreate = document.getElementById("submit");
var message = document.getElementById("message");
var msg = "";
btnCreate.onclick = function() {
if (inputs[0].value === "" || inputs[1].value === "" || inputs[2].value === "") {
emptyInputs(inputs,msg);
}
message.innerHTML = msg;
}
function emptyInputs(input,text) {
for(var i = 0; i < input.length; i++) {
if (input[i].value === "") {
if(!text) {
missing();
}
text += "- " + input[i].name + "<br />";
}
function missing() {
text = "<strong>Please type in:</strong> <br />";
}
}
}
<section id="assignment">
<h1>Add new user</h1>
<form id="newUser">
<div class="inputGroup">
<label for="username">Username</label>
<input type="text" id="username" name="username" />
</div>
<div class="inputGroup">
<label for="password">Password:</label>
<input type="password" id="password" name="password"/>
</div>
<div class="inputGroup">
<label for="passwordConfirm">Confirm password:</label>
<input type="password" id="password2Confirm" name="confirmPassword"/>
</div>
<button id="submit" type="button">Opprett</button>
</form>
<p id="message"></p>
</section>
You were very close to solving your problem. The only thing is, JavaScript doesn't have ouput params.
When you pass an object or array you can modify the content and those changes will be reflect in your calling method. But this doesn't work for strings. Whatever the value of the string is when you use it as a param to call your method, it will still be the value no matter what your method does to it.
var
array = ['hello'],
object = { hello: true },
string = 'hello';
function modifyArray(inputArray) {
inputArray.push('bye');
}
function modifyObject(inputObject) {
inputObject.bye = true;
}
function modifyString(inputString) {
inputString += ', bye';
}
modifyArray(array);
modifyObject(object);
modifyString(string);
// This will print hello and bye
console.log('Content of array after calling method: ', array);
// This will print hello and bye
console.log('Content of object after calling method: ', object);
// This will just print hello
console.log('Content of string after calling method: ', string);
To solve your problem, create a text string inside the method that builds the error message and return that string as the method result.
var assignment = document.getElementById("assignment");
var inputs = assignment.getElementsByTagName('input');
var btnCreate = document.getElementById("submit");
var message = document.getElementById("message");
btnCreate.onclick = function() {
var
// Initialize the error message to an empty string.
msg = '';
// Check if either of the inputs is empty...
if (inputs[0].value === "" || inputs[1].value === "" || inputs[2].value === "") {
// ... and get a custom message prompting the user to fill in the empty data.
msg = emptyInputs(inputs);
}
// Display the error message, or clear it when msg is an empty string.
message.innerHTML = msg;
}
function emptyInputs(input) {
// Initialize the error text.
var
missingPrompt = "<strong>Please type in:</strong> <br />",
text = '';
// Iterate over the provided input elements.
for(var i = 0; i < input.length; i++) {
// Check if the value of the current input is an empty string...
if (input[i].value === "") {
// ... check if the error text is still empty...
if(text === '') {
// ... and if it is start with a default message.
text = missingPrompt;
}
// ... add the field name to the error message.
text += "- " + input[i].name + "<br />";
}
}
// Return the error message.
return text;
}
<section id="assignment">
<h1>Add new user</h1>
<form id="newUser">
<div class="inputGroup">
<label for="username">Username</label>
<input type="text" id="username" name="username" />
</div>
<div class="inputGroup">
<label for="password">Password:</label>
<input type="password" id="password" name="password"/>
</div>
<div class="inputGroup">
<label for="passwordConfirm">Confirm password:</label>
<input type="password" id="password2Confirm" name="confirmPassword"/>
</div>
<button id="submit" type="button">Opprett</button>
</form>
<p id="message"></p>
</section>
Here is the code without msg parameter, and it's working just fine.
var assignment = document.getElementById("assignment");
var inputs = assignment.getElementsByTagName('input');
var btnCreate = document.getElementById("submit");
var message = document.getElementById("message");
var msg = "";
btnCreate.onclick = function() {
msg = "";
if (inputs[0].value === "" || inputs[1].value === "" || inputs[2].value === "") {
emptyInputs(inputs);
}
message.innerHTML = msg;
}
function emptyInputs(input) {
for(var i = 0; i < input.length; i++) {
if (input[i].value === "") {
if(!msg) {
missing();
}
msg += "- " + input[i].name + "<br />";
}
function missing() {
msg = "<strong>Please type in:</strong> <br />";
}
}
}
<section id="assignment">
<h1>Add new user</h1>
<form id="newUser">
<div class="inputGroup">
<label for="username">Username</label>
<input type="text" id="username" name="username" />
</div>
<div class="inputGroup">
<label for="password">Password:</label>
<input type="password" id="password" name="password"/>
</div>
<div class="inputGroup">
<label for="passwordConfirm">Confirm password:</label>
<input type="password" id="password2Confirm" name="confirmPassword"/>
</div>
<button id="submit" type="button">Opprett</button>
</form>
<p id="message"></p>
</section>

Categories

Resources