using local storage with javascript - javascript

I have a signup form that saves user data. The data doesn't save to local storage when it is supposed to. The app is supposed to sign up a user and save the data to the local storage, if someone attempts to sign up with already existing username, the app prevents the user from doing that.
the javascript file does the following
1) prevents users from signing up with already existing username
2) saves an object to the local storage which is passed into an array
var signUpBtn = document.querySelector('#signUp');
var signUpOver = document.querySelector('.signup__overlay');
var signInBtn = document.querySelector('#signIn');
var signInOver = document.querySelector('.signin__overlay');
var fullname = document.querySelector('#name');
var email = document.querySelector('#email');
var password = document.querySelector('#password');
var age = document.querySelector('#age');
var occupation = document.querySelector('#occupation');
var Address = document.querySelector('#address');
var signupSubmitClicked = document.querySelector('#signupClicked');
signupSubmitClicked.addEventListener('click', () => {
if (fullname.value=="" || email.value=="" || password.value=="" || age.value=="" || occupation.value=="" || Address.value=="") {
alert("incomplete datails, please fill up everything")
} else {
alert("item created")
addUser(fullname, email, password, age, occupation, Address);
}
});
var fetchUsers = () => {
try {
var userString = localStorage.getItem('userData');
return JSON.parse(userString);
} catch (error) {
return [];
}
};
var saveUser = (users) => {
localStorage.setItem('userData', JSON.stringify(users));
};
var addUser = (fullname, email, password, age, occupation, Address) => {
var users = fetchUsers();
var user = {
fullname,
email,
password,
age,
occupation,
Address
};
var duplicateUsers = users.filter(user => user.email === email);
if (duplicateUsers.length === 0) {
users.push(user);
saveUser(users);
return user;
}
};
/*************
signup popup
*************/
signUpBtn.addEventListener('click', () => {
signUpOver.style.display = 'block';
});
signUpOver.addEventListener('click', () => {
if(event.target == signUpOver){
signUpOver.style.display = "none";
}
});
/*************
signup popup
*************/
/*************
signin popup
*************/
signInBtn.addEventListener('click', () => {
signInOver.style.display = 'block';
});
signInOver.addEventListener('click', () => {
if(event.target == signInOver){
signInOver.style.display = "none";
}
});
/*************
signin popup
*************/
/** the end */
body {
width: 100%;
margin: 0;
background-color: #F8F9F9;
display: flex;
flex-direction: column;
justify-content: space-around;
align-items: center;
align-content: center;
}
#mainPage,
#userPage {
width: 100%;
display: flex;
flex-direction: column;
justify-content: space-around;
align-items: center;
align-content: center;
}
#userPage {
display: none;
}
/********************
overlay
********************/
.signup__overlay {
position: fixed;
display: none;
top: 0px;
left: 0px;
right: 0px;
bottom: 0px;
background-color: rgba(0,0,0,0.8);
z-index: 1;
}
.signup__content{
position: relative;
width: 100%;
max-width: 520px;
background-color: #ffffff;
opacity: 1;
margin: 64px auto;
padding: 20px;
}
.signin__overlay {
position: fixed;
display: none;
top: 0px;
left: 0px;
right: 0px;
bottom: 0px;
background-color: rgba(0,0,0,0.8);
z-index: 1;
}
.signin__content{
position: relative;
width: 100%;
max-width: 520px;
background-color: #ffffff;
opacity: 1;
margin: 64px auto;
padding: 20px;
}
/********************
overlay ending
********************/
.headerMain {
background-color: #000;
color: #fff;
width: 100%;
margin-bottom: 50px;
height: 50px;
display: flex;
flex-direction: row;
align-items: center;
align-content: center;
justify-content: flex-start;
}
.headerUser {
background-color: #000;
color: #fff;
width: 100%;
margin-bottom: 50px;
height: 50px;
display: flex;
flex-direction: row;
align-items: center;
align-content: center;
justify-content: flex-start;
}
.upButton {
margin-bottom: 20px;
}
.upButton, .inButton {
padding-top: 15px;
padding-bottom: 15px;
cursor: pointer;
width: 100%;
max-width: 200px;
background-color: #239B56;
border: #239B56;
color: snow;
}
label {
padding-top: 20px;
}
label,
input {
width: 100%;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>User system</title>
<link rel="stylesheet" href="css/index.css">
</head>
<body>
<div id="mainPage">
<div class="signup__overlay">
<div class="signup__content">
<form>
<label for="name">Full Name</label>
<input required type="text" id="name" name="name">
<label for="email">Email</label>
<input required type="text" id="email" name="email">
<label for="password">Password</label>
<input required type="password" id="password" name="password">
<label for="age">Age</label>
<input required type="text" id="age" name="age">
<label for="occupation">Occupation</label>
<input required type="text" id="occupation" name="occupation">
<label for="address">Address</label>
<input required type="text" id="address" name="address">
<input type="submit" id="signupClicked">
</form>
</div>
</div>
<div class="signin__overlay">
<div class="signin__content">
<form>
<label for="email">Email</label>
<input required type="text" id="Email" name="email">
<label for="email">Password</label>
<input required type="Password" id="Password" name="Password">
<input type="submit" id="signinClicked">
</form>
</div>
</div>
<header class="headerMain">User System</header>
<section>
<button class="upButton" id="signUp">Sign Up</button>
<button class="inButton" id="signIn">Sign In</button>
</section>
</div>
<div id="userPage">
<header class="headerUser">User System</header>
<section>
</section>
</div>
<script src="js/index.js"></script>
</body>
</html>

Okay so here are several things we need to discuss about. Let's start with the code:
When you have a <input type="submit"> inside a form, the button will re-fresh the page when it's clicked. It's the behaviour by default of the submit button. That's why nothing is stored on the localStorage. To prevent this from happening, you need to use the event.preventDefault() method. Check out this link.
After fixing the preventDefault bug, we face another problem: the function fetchUsers returns null. That's because localStorage.getItem('userData') returns a null if nothing is on the localStorage. The try/catch dosn't work here, since localStorage.getItem('userData') dosn't throw an error. If nothing is there, it simply returns a null (but no error). Solucion: change your return to use a ternary operator:
return JSON.parse(userString) ? JSON.parse(userString) : [];
Using document.querySelector('#name') dosn't return what the user has written on that input. To get what the user writes on an input, you have to use: document.querySelector('#name').value
If you put the var fullname = document.querySelector('#name').value; on the global scope (at the begining of the script) it will take the value that the input had when the script was first loaded (which is... ""). You want to take that value every time the user clicks on the button. So you have to move those variables (fullname, email, password) inside the signupSubmitClicked.addEventListener.
And now the most important thing to discuss: why are you trying to store personal data on the localStorage? You need to be aware that the information on the localStorage is not secure, not really stored into any server, and not recommended at all. If you are doing this project to practice and learn it's okay. You can use this as a playground to learn. But remember: if you want to store personal information in a real-world way, you need to create a server (a back-end to your web).

Hi Opeyemi and welcome on StackOverflow.
First of all you have to know that this way of doing is good for testing, but it won't fit for any production applications.
The reason this is failing is because this function :
var fetchUsers = () => {
try {
var userString = localStorage.getItem('userData');
return JSON.parse(userString);
} catch (error) {
return [];
}
};
is actually returning a null value. Due to that null value, the rest of the code get stuck.
This part of the code will get stuck for example :
var duplicateUsers = users.filter(user => user.email === email);
Normally these errors appear in your console, so you really should check that out.
Once that is fixed it should be pretty easy to fix the rest

Related

looking for why list does not display when adding task to the to do

Good day folks,
I am creating a to-do app, and so far when I enter the task in via the input the console shows my object firing but does not display it on the screen. Please look at my code and help me point out the issue, I have been debugging this for some time today.
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="css/to-doStylesheet.css">
<title>To-Do App</title>
</head>
<body>
<div class=container>
<div class= base>
<div class = screen>
<img src="images/WarGreymon_Render.png" alt="Wargreymon">
<div id ="speach-bubble"> What is on your
agenda for today?
</div>
<div class = "dateTime">
</div>
</div>
<div class = "nameInput" id = "inputContainer">
<form class ="form">
<input type="text" class ="userInput" placeholder="Add Agenda and press enter">
<input type="submit" value ="Add">
</form>
</div>
</div>
<ul class="list"></ul>
<script src="js/add-task.js"></script>
</body>
</html>
CSS
.form
{
margin-left: 400px;
}
.userInput
{
width: 394px;
height: 30px;
background-color: #B62626;
font-family: Digimon Basic;
color: #33D61A;
margin-left: -359px;
}
.userInput ::placeholder
{
color: #33D61A;
font-family: Digimon Basic;
}
.list:empty
{
display: none;
}
.list
{
list-style: none;
margin-bottom: 20px;
}
.input[type="checkbox"] {
display: none;
}
.tick {
width: 30px;
height: 30px;
border: 3px solid #333;
border-radius: 50%;
display: inline-flex;
justify-content: center;
align-items: center;
cursor: pointer;
}
.todo-item {
margin-bottom: 10px;
width: 100%;
display: flex;
align-items: center;
justify-content: space-between;
}
.todo-item span {
flex-grow: 1;
margin-left: 10px;
margin-right: 10px;
font-size: 22px;
}
JS
let tasks = [];
const currentdt = new Date()
function todo(text) {
const todo = {
text,
checked: false,
id: Date.now(),
timestamp: currentdt
};
tasks.push(todo);
console.log(tasks);
}
// Select the form element
const form = document.querySelector('.form');
// Add a submit event listener
form.addEventListener('submit', event => {
// prevent page refresh on form submission
event.preventDefault();
// select the text input
const input = document.querySelector('.userInput');
// Get the value of the input and remove whitespace
const text = input.value.trim();
if (text !== '') {
todo(text);
input.value = '';
input.focus();
}
});
//This function is to display new to do on the screen
function displaytasks(todo)
{
const list = document.querySelector('list');
const isChecked = todo.checked ? 'done': '';
const addedList = document.createElement("li");
addedList.setAttribute('class', `todo-item ${isChecked}`);
addedList.setAttribute('data-key', todo.timestamp);
addedList.innerHTML = `<input id="${todo.timestamp}" type="checkbox"/>
<label for="${todo.timestamp}" class="tick js-tick"></label>
<span>${todo.text}</span>
<button class="delete-todo js-delete-todo">
<img class = "delete" src="images/delete.png" alt="delete icon">
</button>`;
list.append(addedList);
}
So I am busy with the js file at the moment, I think it has to do something with the innerHTML, but I am not sure what exactly is wrong there, because when I look in the console on the HTML side I do not see the <ul class="list"></ul> firing at all to bring the new HTML elements.
Your help will be much appreciated
It looks like the code to display the todos is not being called, so I would recommend you add in a function call after reading in a new todo.
...
const text = input.value.trim();
if (text !== '') {
todo(text);
input.value = '';
input.focus();
displaytasks(tasks); // Show tasks after submission
}
});
//This function is to display new to do on the screen
function displaytasks(todo)
{
const list = document.querySelector('.list');
...

Enter the prototype of an Object.prototype.function(), where all the EventListeners are safed (Javascript)

I am working on an assignment, that constructs a small library. The project requires, that the user can input the title of a book, its author, number of pages and if the user has already read it. Then the content gets displayed on the page.
Here's the code (work in progress):
let myLibrary = [];
let submitBtn = document.querySelector("#submitBtn");
let textInput = document.querySelectorAll("input");
let addNew = document.getElementById("addNew");
let fieldSet = document.getElementById("fieldset");
let cancelBtn = document.querySelector("#cancelBtn");
let bookDisplay = document.getElementById("bookDisplay");
let flexItems = document.getElementsByClassName("flexItems");
// object Constructor for new books
class Book {
constructor(title, author, pages, read) {
this.title = title;
this.author = author;
this.pages = pages;
this.read = read;
}
}
Book.prototype.addToDisplay = function() {
let newDiv = document.createElement("div");
bookDisplay.appendChild(newDiv).className = "flexItems";
let newSpan = document.createElement("span");
flexItems[myLibrary.length-1].appendChild(newSpan).className = "spanItem";
newSpan.innerText = this.title;
this.read === true ? flexItems[myLibrary.length-1].style.backgroundColor = "green" :
flexItems[myLibrary.length-1].style.backgroundColor = "red";
newDiv.addEventListener("mouseenter", moreInfo => {
newSpan.childNodes[0].nodeValue = this.author + "\n" + this.title + "\n" + this.pages + " pages";
})
newDiv.addEventListener("mouseleave", defaultInfo => {
newSpan.childNodes[0].nodeValue = this.title;
})
}
// creates a new instance of Book and pushes the object into the array
let addToLibrary = function addToLibrary() {
newBook = new Book(textInput[0].value, textInput[1].value, textInput[2].value, textInput[3].checked)
myLibrary.push(newBook);
newBook.addToDisplay();
};
// eventlistener, to submit a new Book to the library
submitBtn.addEventListener("click", addToLibrary);
// sets the form's display from block to non-visible
let cancel = function cancel() {
fieldSet.style.display = "none";
}
// cancels the form and returns back
cancelBtn.addEventListener("click", cancel);
// sets the form's display from non-visible to visible
let openForm = function openForm() {
fieldSet.style.display = "block";
}
// opens form to add new book
addNew.addEventListener("click", openForm);
body {
margin-left: 20px;
}
h1 {
text-align: center;
}
#fieldset {
position: fixed;
z-index: 2;
border: none;
display: none;
background: #3CBC8D;
border-radius: 10px;
right: 1%;
top: 2%;
width: 400px;
height: auto;
overflow: auto;
}
button {
cursor: pointer;
}
.display {
display: flex;
flex-direction: row;
flex-wrap: wrap;
position: relative;
}
.flexItems {
position: relative;
display: flex;
margin: 5px;
color: black;
font: Georgia;
font-size: 20px;
height: 200px;
width: 200px;
align-items: center;
border: 2px solid gray;
transition: 500ms;
border-radius: 5px;
}
.spanItem {
width: 100%;
text-align: center;
white-space: wrap;
overflow: hidden;
text-overflow: ellipsis;
}
.display .flexItems:focus,
.display .flexItems:hover {
transform: scale(1.2);
z-index: 1;
}
#addNew {
position: fixed;
z-index: 2;
border: none;
background: #3CBC8D;
color: white;
border-radius: 10px;
right: 2%;
top: 2%;
width: 100px;
height: 50px;
overflow: auto;
cursor: pointer;
}
/*. Could be additionally used for the hover-effect, but doesnt look that nice for more than one row
flexItems:hover ~.flexItems {
transform: translateX(25%);
}
.display:focus-within .flexItems,
.display:hover .flexItems {
transform: translateX(-25%);
}
.flexItems:focus ~.flexItems,
.flexItems:hover ~.flexItems {
transform: translateX(25%);
} */
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<link href="style.css" rel="stylesheet" type="text/css" />
<script src="script.js" defer></script>
<title>Library</title>
</head>
<body>
<div><h1>My book library</h1></div>
<div id="bookDisplay" class="display">
</div>
<div>
<button id="addNew">Test</button>
</div>
<fieldset id="fieldset">
<form id="form">
<div>
<label for="title">Title: </label>
<input type="text" name="title" id="title" class="usrInput">
</div>
<div>
<label for="author">Author: </label>
<input type="text" name="author" id="author" class="usrInput">
</div>
<div>
<label for="number">Number of pages: </label>
<input type="number" name="number" id="number" class="usrInput">
</div>
<div>
<label for="read">Already read?: </label><br>
Y <input type="radio" name="read" id="read" value="Y" class="read">
N <input type="radio" name="read" id="read" value="N" class="read">
</div>
<button id="submitBtn" type="button">Submit</button>
<button id="cancelBtn" type="button">Cancel</button>
</fieldset>
</div>
</body>
</html>
**My question: ** The code is working until here. But I have my concerns with the mouseenter-Eventlistener. On mouseenter, I want to add a <button>, to edit the book's value. And maybe there is moreto be added in the future. That would mean the àddToDisplay() function eventually will get clunky. So I was wondering, if I could enter the Object.prototype of the addToDisplay() function and store all eventListeners in its prototype. Is this possible in Javascript?
The only way I could solve it right now is, to write an extra function for the eventlisteners. But it seems, that this way, I'm just going back to normal function expressions with dozens of values to pass by:
Book.prototype.addToDisplay = function() {
// (...)
mousehover(this, newDiv, newSpan)
}
let mousehover = function mousehover(test, newDiv, newSpan) {
newDiv.addEventListener("mouseenter", moreInfo => {
newSpan.childNodes[0].nodeValue = test.author + "\n" + test.title + "\n" + test.pages + " pages";
})
newDiv.addEventListener("mouseleave", defaultInfo => {
newSpan.childNodes[0].nodeValue = test.title;
})
}
Hope I got the problem across. It's the first assignment to Objects I'm working on.
Thanks for any answers and links to informative sources.

Javascript Firebase-Storage image upload not working

I am trying to upload an image from HTML form to firebase storage using an external JS file, but when I try to upload the image file (which is not empty - it exists) the path to the image location is not created on firebase storage when I execute the storageRef.put(image); function, and also the image itself (obviously) not being saved.
this is my code:
index.html file:
<!DOCTYPE html>
<html>
<head>
<title>אורט ביאליק עדכון פרטים</title>
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.4.1/css/all.css" integrity="sha384-5sAR7xN1Nv6T6+dT2mhtzEpVJvfS3NScPQTrOxhwjIuvcA67KV2R5Jz6kr4abQsz" crossorigin="anonymous">
<link href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700" rel="stylesheet">
<style>
html, body {
min-height: 100%;
direction: rtl
}
body, div, form, input, select, p {
padding: 0;
margin: 0;
outline: none;
font-family: Roboto, Arial, sans-serif;
font-size: 16px;
color: #eee;
}
body { background: url("https://firebasestorage.googleapis.com/v0/b/XXXXXXXX.appspot.com/o/not%20to%20delete%2Fbackground.jpeg?alt=media&token=b5e0cc70-dc1c-40c7-a3fa-15694541828e") no-repeat center; background-size: cover; }
h1, h2 {
text-transform: uppercase;
font-weight: 400;
}
h2 {
margin: 0 0 0 8px;
}
.main-block {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
height: 100%;
padding: 25px;
background: rgba(0, 0, 0, 0.5);
}
.left-part, form {
padding: 25px;
}
.left-part {
text-align: center;
}
.fa-graduation-cap {
font-size: 72px;
}
form {
background: rgba(0, 0, 0, 0.7);
}
.title {
display: flex;
align-items: center;
margin-bottom: 20px;
}
.info {
display: flex;
flex-direction: column;
}
input, select {
padding: 5px;
margin-bottom: 30px;
background: transparent;
border: none;
border-bottom: 1px solid #eee;
}
input::placeholder {
color: #eee;
}
option:focus {
border: none;
}
option {
background: black;
border: none;
}
.btn-item, button {
padding: 10px 5px;
margin-top: 20px;
border-radius: 5px;
border: none;
background: #26a9e0;
text-decoration: none;
font-size: 15px;
font-weight: 400;
color: #fff;
}
.btn-item {
display: inline-block;
margin: 20px 5px 0;
}
button {
width: 100%;
}
button:hover, .btn-item:hover {
background: #85d6de;
}
#media (min-width: 568px) {
html, body {
height: 100%;
}
.main-block {
flex-direction: row;
height: calc(100% - 50px);
}
.left-part, form {
flex: 1;
height: auto;
}
}
</style>
</head>
<body>
<div class="main-block">
<div class="left-part">
<img src="https://firebasestorage.googleapis.com/v0/b/XXXXXXXXX.appspot.com/o/not%20to%20delete%2Fkiryat_bialik_img.jpg?alt=media&token=5d637243-1cb1-430c-a7c5-1a98329bb3a0">
</div>
<form name="RegForm" action="/">
<div class="title">
<i class="fas fa-pencil-alt"></i>
<h2>מכללת אורט ביאליק - עדכון פרטים אישיים</h2>
</div>
<div class="info">
<input class="fname" type="text" name="HEfname" id="HEfname" maxlength="20" required autofocus placeholder="שם פרטי">
<input class="fname" type="text" name="HElname" id="HElname" maxlength="20" required placeholder="שם משפחה">
<input class="fname" type="text" name="ENfname" id="ENfname" maxlength="20" required placeholder="שם פרטי באנגלית">
<input class="fname" type="text" name="ENlname" id="ENlname" maxlength="20" required placeholder="שם משפחה באנגלית">
<input type="text" name="Email" inputmode="email" id="email" required maxlength="40" placeholder="Email">
<input type="text" name="id" id="id" required maxlength="9" placeholder="מספר תעודת זהות">
<input type="file" name="img" id="img" required accept="image/*">
</div>
<button type="submit" name="submit" id="submit" value="submit" onclick="return validation();" href="/">שלח</button>
</form>
</div>
<!-- The core Firebase JS SDK is always required and must be listed first -->
<script src="https://www.gstatic.com/firebasejs/7.8.2/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.8.2/firebase-database.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.8.2/firebase-storage.js"></script>
<script src="js/formValidation.js"></script>
<script src="js/formSubmission.js"></script>
</body>
</html>
formSubmission.js:
// My web app's Firebase configuration
var firebaseConfig = {
apiKey: "XXXXXXXXXXXX",
authDomain: "XXXXXXXXXXXX.firebaseapp.com",
databaseURL: "https://XXXXXXXXXXXX.firebaseio.com",
projectId: "XXXXXXXXXXXX",
storageBucket: "XXXXXXXXXXXX.appspot.com",
messagingSenderId: "XXXXXXXXXXXX",
appId: "XXXXXXXXXXXX"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
// Reference Users collection
var databaseRef = firebase.database().ref('Users');
// Listen for form submit
document.forms.RegForm.addEventListener('submit', submitForm);
// Submit form
function submitForm() {
//if (validation()) {
// Get values
var HEfname = getInputVal('HEfname');
var ENfname = getInputVal('ENfname');
var HElname = getInputVal('HElname');
var ENlname = getInputVal('ENlname');
var email = getInputVal('email');
var id1 = getInputVal('id');
var imageFile = document.getElementById('img').files[0];
//this VAR's are used in 'saveUser()'; function. ---NOT IN USE---
// unused value=5; if false value=0; if true value=1
var isSavedDatabase = false; // if user data successfully commited to Firebase Database.
var isSavedImage = false; // if user image successfully commited to Firebase Storage.
// Save User
saveUser(HEfname, HElname, ENfname, ENlname, email, id1, imageFile);
}
// Function to get get form values
function getInputVal(id) {
return document.getElementById(id).value;
}
// Save User to firebase
function saveUser(HEfname, HElname, ENfname, ENlname, email, id1, imageFile) {
// reference to image path in storage 'passportImages/id1' (id1 is current user ID)
var imageRef = firebase.storage().ref().child('passportImages/' + id1);
//save User to database
var newUserRef = databaseRef.child(id1);
newUserRef.set({
HEfname: HEfname,
HElname: HElname,
ENfname: ENfname,
ENlname: ENlname,
email: email,
id: id1
}, function (error) {
if (error) {
// The write failed
console.log("User info could not be saved: " + error);
} else {
// Data saved successfully!
isSavedDatabase = true;
console.log("User info saved successfully!");
saveImage(imageFile, id1);
//imageRef.delete(); // remove user image from storage if his info could not be saved t database.
}
});
//save image to storage by ID
function saveImage(imageFile, id) {
// Upload file to the object 'passportImages/id1' (id1 is current user ID)
var uploadTask = firebase.storage().ref().child('passportImages/' + id).put(imageFile);
// Listen for state changes, errors, and completion of the upload.
uploadTask.on(firebase.storage.TaskEvent.STATE_CHANGED, // or 'state_changed'
function (snapshot) {
// Get task progress, including the number of bytes uploaded and the total number of bytes to be uploaded
var progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
console.log('Upload is ' + progress + '% done');
switch (snapshot.state) {
case firebase.storage.TaskState.PAUSED: // or 'paused'
console.log('Upload is paused');
break;
case firebase.storage.TaskState.RUNNING: // or 'running'
console.log('Upload is running');
break;
}
}, function (error) {
databaseRef.child(id).remove(); //remove user info from database if his image could not be uploaded to storage too.
console.log(error);
window.alert("Something went wrong, please try again");
// A full list of error codes is available at
// https://firebase.google.com/docs/storage/web/handle-errors
switch (error.code) {
case 'storage/unauthorized':
// User doesn't have permission to access the object
console.log("Image: User doesn't have permission to access the object");
break;
case 'storage/canceled':
// User canceled the upload
console.log("Image: User canceled the upload");
break;
case 'storage/unknown':
// Unknown error occurred, inspect error.serverResponse
console.log("Image: Unknown error occurred, inspect error.serverResponse");
break;
}
}, function () {
// Upload completed successfully!
isSavedImage = true;
console.log("Image uploaded successfully!");
finalCall();
});
//if all data commited successfully to Firebase pop a massage and reset form.
function finalCall() {
// Show alert
window.alert("Your info has been sent!");
// Clear form
document.forms.RegForm.reset();
}
}
//}
}
It is probably because you assign the submit type to your button. Your form is probably submitted before the submitForm() method is triggered.
If this assumption is correct, changing the type to button, as follows, should do the trick:
<button type="button" id="submit" onclick="return validation();" href="/">שלח</button>
See the W3 specification for more detail.

input type password is immovable

I have this code and the 1st input won't ever move whatever I do the only thing that made it move was float:right; but I don't want it to be like this I even created this div->P so maybe it would move. Has anyone encountered this problem before?
Is it possibly interfearing with my js? That's the only thing I can think of rn
.inner {
display:inline-block;
margin-right:500px;
}
.pswd {
display:inline-block;
margin-right:500px;
}
</style>
</head>
<body>
<div class="P">
<input class="inner" type="password" id="pswd">
<input class="inner" type="button" value="Submit" onclick="checkPswd();"/>
</div>
<script type="text/javascript">
function checkPswd() {
var confirmPassword = "admin";
var password = document.getElementById("pswd").value;
if (password == confirmPassword) {
window.location="A.html";
}
else{
alert("Password incorrect.");
}
}
</script>
This should work if you use the ID selector rather than the class selector (i.e. use # rather than .):
#pswd {
display:inline-block;
margin-right:500px;
}
There are multiple ways to center-align a div both vertically and horizontally on the screen.
I have used display:flex for the same.
'use-strict'
function checkPswd(form) {
const confirmPassword = "admin";
let passwordProvided = form.elements.newPassword.value;
if (passwordProvided === confirmPassword) {
// If correct
} else {
// If failure
}
// to prevent default action
return false;
}
.form--wrapper {
width: 150px;
height: 150px;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
}
form {
display: flex;
flex-direction: column;
justify-content: center;
height: 100%;
width: 100%;
border: 2px dashed orange
}
<div class="form--wrapper">
<form name="change-password" onsubmit="return checkPswd(this)">
<input class="inner" name="newPassword" type="password">
<input class="inner" type="submit" value="Submit" />
</form>
</div>

Does anyone know why my multi-phase form won't work?

I am making a multi-phase form but it is not acting normal
I have written a lot of diffrent code for it but don't know why it is not working the way I want it
It has been two days working with it I am feeling stupid now
here is the code
HTML:
<div id="form-container">
<div id="phase-1">
<h3>Phase 01</h3>
<form>
<input id="fname" type="text" placeholder="First name">
<input id="lname" type="text" placeholder="Last name">
<input id="email" type="text" placeholder="Email">
<button id="phase-1-btn">Next</button>
</form>
</div>
<div id="phase-2">
<h3>Phase 02</h3>
<form>
<input id="pass" type="text" placeholder="Password">
<input id="cpass" type="text" placeholder="Confirm Password">
<button id="phase-2-btn">Next</button>
</form>
</div>
<div id="phase-3">
<h2>Thank You for Testing my pen</h2>
</div>
</div>
CSS :
#form-container{
height: 350px;
width: 300px;
margin-top: 80px;
margin-left: auto;
margin-right: auto;
background-color: #95a5a6;
font-family: "Slabo 27px";
position: relative;
box-shadow: 1px 1px 2px,
-1px -1px 2px;
}
#phase-1, #phase-2{
height: 100%;
width: 100%;
border-top: 3px solid #f39c12;
display: block;
}
#phase-1 h3, #phase-2 h3{
height: 10%;
width: 60%;
margin-left: auto;
margin-right: auto;
text-align: center;
font-size: 23px;
color: #fff;
}
#phase-1 form, #phase-2 form{
display: block;
height: 75%;
padding: 0;
padding-top: 15px;
margin: 0;
}
input{
display: block;
width: 80%;
margin-top: 10px;
margin-left: auto;
margin-right: auto;
padding: 10px 20px;
border: none;
border-radius: 5px;
}
button {
display: block;
width: 60%;
margin-left: auto;
margin-right: auto;
margin-top: 20px;
padding: 10px 5px;
background-color: #f39c12;
color: #fff;
font-weight: 600;
border: none;
border-radius: 6px;
}
#phase-2{
display: none;
}
#phase-3{
display: none;
height: 0;
width: 100%;
color: #000;
position: absolute;
top: 0;
left: 0;
background: #f39c12
}
#phase-3 h2{
width: 200px;
height: 60px;
margin-left: auto;
margin-right: auto;
margin-top: 135px;
text-align: center;
}
JS :
var fname, lname, email, pass, cpass;
function id( id ) {
return document.getElementById(id);
}
function phase1 () {
fname = id("fname").value;
lname = id("lname").value;
email = id("email").value;
if ( fname.length > 2 && lname.length > 2 && email.length > 2 ) {
id("phase-1").style.display = "none";
id("phase-2").style.display = "block";
// end of if
} else {
alert("Please fill the Form");
}
} // end of phase1 function
// add the event to the phase-1-btn
id("phase-1-btn").addEventListener("click", phase1());
/* phase 02 */
function phase2 () {
pass = id("pass").value;
cpass = id("cpass").value;
if ( pass.length > 2 && cpass.length > 2 ) {
id("phase-2").style.display = "none";
id("phase-3").style.display = "block";
id("phase-3").style.height = "100%";
// end of if
} else {
alert("Please fill the Form");
}
} // end of phase2 function
id("phase-2-btn").addEventListener("click", phase2());
Let's try this one. Then tell me what you see in the console.
<script>
function phase1()
{
window.console.log('phase1 function called');
var fname_val = document.getElementById('fname').value;
var lname_val = document.getElementById('lname').value;
var email_val = document.getElementById('email').value;
// verify values
window.console.log('fname_val='+fname_val + ' lname_val='+lname_val + ' email_val='+email_val);
if( fname_val.length > 2 && lname_val.length > 2 && email_val.length > 2 )
{
window.console.log('validation!! :)');
document.getElementById("phase-1").style.display = "none";
document.getElementById("phase-2").style.display = "block";
}
else
{
alert("Please fill the Form");
}
}
function phase2()
{
window.console.log('phase2 function called');
}
document.addEventListener("DOMContentLoaded", function(event) {
window.console.log("DOM fully loaded and parsed");
document.getElementById("phase-1-btn").addEventListener("click", phase1);
document.getElementById("phase-2-btn").addEventListener("click", phase2);
});
</script>
<div id="phase-1">
<h3>Phase 01</h3>
<input id="fname" type="text" placeholder="First name" />
<input id="lname" type="text" placeholder="Last name" />
<input id="email" type="text" placeholder="Email" />
<input type="button" id="phase-1-btn" value="Next" />
</div>
<div id="phase-2">
<h3>Phase 02</h3>
<input id="pass" type="text" placeholder="Password" />
<input id="cpass" type="text" placeholder="Confirm Password" />
<input type="button" id="phase-2-btn" value="Next" />
</div>
<div id="phase-3">
<h2>Thank You for Testing my pen</h2>
</div>
To submit a form you want to use a submit button (not classic button).
Have all of your inputs within the form tags.
Add the appropriate form tag attributes such as (action & method)
Use one form tag that wraps around everything with the submit button on the inside.
CSS will have no effect so no need to share that part.
Last but not least - Dont call yourself stupid. Stupid people never ask for help. Reaching out for help is how you improve your skillset.
If you insist on using Javascript to submit the form that is fine, but you want to make sure the form works with classic HTML first.
To make this a multi-step process you should try doing 1 form per page. You will need to understand session handling. You can display portions of the form at a time with Javascript which gives an impression of doing steps but still using 1 form.
<form action="" method="POST">
<script>
function toggleSection(x){
document.getElementById('sec'+x).style.display = "block";
}
</script>
<div id="sec1">
section 1 stuff
<input type="button" value="Continue" onclick="toggleSection(2);" />
</div>
<div id="sec2" style="display:none;">
section 2 stuff
<input type="button" value="Continue" onclick="toggleSection(3);" />
</div>
<div id="sec3" style="display:none;">
section 3 stuff
<input type="submit" value="Submit" />
</div>
</form>
here it is with the changes you ordered
var fname, lname, email, pass, cpass;
function el( id ) {
return document.getElementById(id);
}
function phase1 () {
fname = el("fname").value;
lname = el("lname").value;
email = el("email").value;
if ( fname.length > 2 && lname.length > 2 && email.length > 2 ) {
el("phase-1").style.display = "none";
el("phase-2").style.display = "block";
// end of if
} else {
alert("Please fill the Form");
}
} // end of phase1 function
// add the event to the phase-1-btn
el("phase-1-btn").addEventListener("click", phase1);
/* phase 02 */
function phase2 () {
pass = el("pass").value;
cpass = el("cpass").value;
if ( pass.length > 2 && cpass.length > 2 ) {
el("phase-2").style.display = "none";
el("phase-3").style.display = "block";
el("phase-3").style.height = "100%";
// end of if
} else {
alert("Please fill the Form");
}
} // end of phase2 function
el("phase-2-btn").addEventListener("click", phase2);

Categories

Resources