Verifying existing users in local storage - javascript

I created a website that saves user data on the local storage. it works well, but I wrote an if else statement to handle people signing up with existing email. I do not know why the code doesn't work. I created a variable duplicateUsers followed by the if else statement. below are the HTML CSS and javascript code.
the javascript file does the following
1) adds a user to the local storage by clicking the signup button
2) checks for incomplete details
3) checks for duplicate users and performs an action based on the response (doesn't work)
the problem here is that regardless of whether the user already exists, it still adds the user to the local storage instead of returning an alert saying the user already exists.
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 addUser = (fullname, email, password, age, occupation, address) => {
var users = [];
const user = {
fullname: fullname.value,
email: email.value,
password: password.value,
age: age.value,
occupation: occupation.value,
address: address.value
};
try {
var existingUsers = localStorage.getItem('userData');
users = JSON.parse(existingUsers) || [];
} catch (e) {
}
var duplicateUsers = users.filter(user => user.email === email);
if (duplicateUsers.length === 0) {
users.push(user);
localStorage.setItem('userData', JSON.stringify(users));
} else {
alert("user already exists");
}
};
/*************
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>

Related

Vanilla JS budget app delete dynamically rendered income or expense

I've made a budgeting app that has expenses and Income tabs. Every time you add an expense or income, the app pushes the information inside of an array of objects and dynamically renders an <li> component and places it inside of a <ul>. I'm having trouble with the edit and delete features. Each individual <li> comes with a delete and edit button. The <li>, delete button, and edit button all have the same id of Date.now(). Date.now() is used because it produces a number based on milliseconds and won't produce the same id twice unless someone types an expense or income twice within one millisecond I want to click on the delete button inside of the <li> and have my app remove that individual object from my entry_list[] array and also remove the <li> from the DOM.
'use strict'
const balanceElement = document.querySelector(".balance .value");
const totalIncome = document.querySelector(".income-total");
const totalOutcome = document.querySelector(".outcome-total");
const incomeElement = document.querySelector(".income-tab");
const expense = document.querySelector(".expense-tab");
const all = document.querySelector(".all-tab");
const incomeList = document.querySelector(".income-tab .list");
const expenseList = document.querySelector(".expense-tab .list");
const allList = document.querySelector(".all-tab .list");
const expensesButton = document.querySelector(".tab1");
const incomeButton = document.querySelector(".tab2");
const allButton = document.querySelector(".tab3");
const addExpense = document.querySelector(".add-expense")
const expenseTitle = document.querySelector(".expense-title-input")
const expenseAmount = document.querySelector(".expense-amount-input")
const addIncome = document.querySelector(".add-income")
const incomeTitle = document.querySelector(".income-title-input")
const incomeAmount = document.querySelector(".income-amount-input")
const list = document.querySelector('.list')
//SWITCHING BETWEEN TABS
expensesButton.addEventListener('click', () => {
expense.classList.remove('hidden');
incomeElement.classList.add('hidden');
expensesButton.classList.add('clicked');
incomeButton.classList.remove('clicked');
})
incomeButton.addEventListener('click', () => {
incomeElement.classList.remove('hidden');
expense.classList.add('hidden');
expensesButton.classList.remove('clicked');
incomeButton.classList.add('clicked');
})
incomeList.addEventListener('click', deleteOrEdit)
expenseList.addEventListener('click', deleteOrEdit)
let entry_list = []
addExpense.addEventListener('click', () =>{
if(expenseTitle.value == '' || expenseAmount.value == ''){
return;
}
let expense = {
type: 'expense',
title: expenseTitle.value,
amount: expenseAmount.value,
id: Date.now()
}
entry_list.push(expense)
clearExpense()
changeLists()
})
addIncome.addEventListener('click', () =>{
if(incomeTitle.value == '' || incomeAmount.value == ''){
return;
}
let income = {
type: 'income',
title: incomeTitle.value,
amount: incomeAmount.value,
id: Date.now()
}
entry_list.push(income)
clearIncome()
changeLists()
})
const clearExpense = () =>{
expenseTitle.value = '';
expenseAmount.value = '';
}
const clearIncome = () =>{
incomeTitle.value = ''
incomeAmount.value = ''
}
const changeLists = () =>{
expenseList.innerHTML = ''
incomeList.innerHTML = ''
entry_list.map((entry) =>{
if(entry.type == 'expense'){
return expenseList.innerHTML += `<li id = "${entry.id}" class= "${entry.type}">
<div class = "entry">${entry.title}: $${entry.amount}</div>
<div class="icon-container">
<div class = "edit" id="${entry.id}"></div>
<div class ="delete" id="${entry.id}"></div>
</div>
</li>`
}
else if(entry.type == 'income'){
return incomeList.innerHTML += `<li id = "${entry.id}" class= "${entry.type}">
<div class = "entry">${entry.title}: $${entry.amount}</div>
<div class="icon-container">
<div class = "edit" id="${entry.id}"></div>
<div class ="delete" id="${entry.id}"></div>
</div>
</li>`
}
})
addIncomes()
}
const addIncomes = () =>{
let sum = 0;
let income = 0;
let outcome = 0;
balanceElement.innerHTML = 0
totalIncome.innerHTML = 0
totalOutcome.innerHTML = 0
entry_list.forEach(list =>{
if(list.type == 'expense'){
sum -= list.amount
outcome -= list.amount
}else if(list.type == 'income'){
sum += Number(list.amount)
income += Number(list.amount)
}
balanceElement.innerHTML = '$' + sum
totalIncome.innerHTML = '$' + income
totalOutcome.innerHTML = '$' + outcome
})
}
// // DETERMINE IF BUTTON IS EDIT OR DELETE
function deleteOrEdit(e){
const targetButton = e.target;
const entry = targetButton.parentNode.parentNode;
if(targetButton.classList == ('delete')){
deleteEntry(entry)
}else if(targetButton.classList == ('edit')){
editEntry(entry);
}
}
// //DELETE FUNCTION
const deleteEntry = (entry) =>{
console.log(entry.id)
entry_list.splice(entry.id, 1)
// entry.innerHTML = ''
console.log(entry.id)
addIncomes()
}
// EDIT FUNCTION
const editEntry = (entry) =>{
let Entry = entry_list[entry.id]
if(entry.type == "income"){
incomeAmount.value = Entry.amount;
incomeTitle.value = Entry.title;
}else if(entry.type == "expense"){
expenseAmount.value = Entry.amount;
expenseTitle.value = Entry.title;
}
deleteEntry(entry);
}
#import url('https://fonts.googleapis.com/css2?family=Open+Sans:wght#400;700&family=Raleway:wght#400;700&display=swap');
*{
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: 'Open Sans', sans-serif;
}
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
-webkit-appearance: none;
margin: 0;
}
.budget-container{
display: flex;
align-items: center;
justify-content: center;
height: 100vh;
width: 100%;
background-color: #4F98CA;
}
.balance-container{
width: 360px;
height: 470px;
background-color: #50D890;
border-radius: 30px;
margin-right: 100px;
}
.app-title{
color: white;
margin-top: 1rem;
margin-left: 1rem;
}
.month{
color: white;
margin-top: 1rem;
text-align: center;
}
.budget-header{
display: flex;
flex-direction:column;
justify-content: center;
}
.balance{
margin-top: 1rem;
margin-left: 1rem;
}
.title{
color: white;
font-size: 1.25rem;
opacity: .75;
}
.value{
font-size: 1.75rem;
color: white;
font-weight: bold;
margin-left: 1rem;
}
.account{
margin-top: 2.5rem;
margin: 2.5rem 1.5rem 2.5rem 1.5rem;
display: flex;
justify-content: space-between
}
.income-total{
color: white;
text-align: center;
font-size: 1.5rem;
}
.outcome-total{
color: #4F98CA;
text-align: center;
font-size: 1.5rem;
}
/* DASHBOARD */
.budget-dashboard{
display: block;
width: 360px;
height: 470px;
position: relative;
border-radius: 30px;
background-color: white;
}
.dash-title{
margin-top: 2rem;
margin-left: 1rem;
font-size: 1.5rem;
}
.toggle{
margin: 1rem;
display: flex;
cursor: pointer;
}
.toggle .tab2, .tab3{
margin-left: 1rem;
cursor: pointer;
}
.clicked{
font-weight: bold !important;
}
.hidden{
display: none !important;
}
/* EXPENSES TAB */
.expense-tab{
display: flex;
justify-content: center;
}
.expense-input-container{
position: absolute;
top: 400px;
border-top: solid 1px gray;
width: 100%;
}
.expense-amount-input{
width: 125px;
border: none;
outline: none;
font-size: 1.25rem;
}
.expense-title-input{
width: 125px;
border: none;
outline: none;
font-size: 1.25rem;
}
.add-expense{
color: none;
background-color: none;
border: none;
outline: none;
color: inherit;
}
/* INCOME TAB */
.income-tab{
display: flex;
justify-content: center;
}
.income-input-container{
position: absolute;
top: 400px;
border-top: solid 1px gray;
width: 100%;
}
.input{
display: flex;
justify-content: space-between;
align-items: center;
margin: 1rem;
}
.income-amount-input{
width: 125px;
border: none;
outline: none;
font-size: 1.25rem;
}
.income-title-input{
width: 125px;
border: none;
outline: none;
font-size: 1.25rem;
}
.add-income{
color: none;
background-color: none;
border: none;
outline: none;
}
.plus-img{
width: 40px;
}
/* li */
ul{
width: 360px;
height: 255px;
list-style: none;
margin-top:20px;
overflow-x: auto;
}
/* BUTTON ICONS */
.edit{
background-image: url('media/Icons/icons8-edit-48.png');
background-size: contain;
width: 25px;
height: 25px;
background-repeat: no-repeat;
margin-right: 10px;
}
.delete{
background-image: url('media/Icons/icons8-trash-can-48 (2).png');
background-size: contain;
width:25px;
height: 25px;
background-repeat: no-repeat;
}
.income{
width:250px;
height: auto;
padding-left: 20px;
margin-bottom: 10px;;
word-wrap: break-word;
color: black
}
.expense{
width:250px;
height: auto;
padding-left: 20px;
margin-bottom: 10px;;
word-wrap: break-word;
font-family: 'Gilroy Bold';
color: #4F98CA;
}
li{
display: flex;
justify-content: space-between;
width: 100% !important;
padding-right: 20px;
}
.icon-container{
display: flex;
}
#media (max-width:900px){
.budget-container{
display: inline-block;
position: relative
}
.balance-container{
position: absolute;
top: 10%;
left: 25%;
}
.budget-dashboard{
position: absolute;
left: 25%;
top: 40%;
}
}
<!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="style.css">
<title>Budgetrr</title>
</head>
<body>
<main class="budget-container">
<section class="balance-container">
<div class="app-title">
<p>Budgetrr</p>
</div>
<h1 class="month">OCTOBER</h1>
<section class="budget-header">
<div class="balance">
<div class="title">
Balance
</div>
<div class="value">
<small>$</small>0
</div>
</div>
<div class="account">
<div class="budget-income">
<div class="title">
Income
</div>
<div class="income-total">
<small>$</small>0
</div>
</div>
<div class="chart"></div>
<div class="budgetoutcome">
<div class="title">
Expenses
</div>
<div class="outcome-total">
<small>$</small>0
</div>
</div>
</div>
</section>
</section>
<section class="budget-dashboard">
<div class="dash-title">Dashboard</div>
<div class="toggle">
<div class="tab1 clicked">Expenses</div>
<div class="tab2">Income</div>
<!-- <div class="tab3 clicked">All</div> -->
</div>
<div class="income-tab hidden">
<ul class="list"></ul>
<div class="income-input-container">
<form class="input">
<input type="text" class="income-title-input" name="title" placeholder="Title">
<input type="number" class="income-amount-input" name="amount" placeholder="$0">
<button type = "button" class="add-income"><img class= "plus-img"src="media/Icons/icons8-add-new-48.png" alt=""></button>
</form>
</div>
</div>
<div class = "expense-tab">
<ul class="list"></ul>
<div class="expense-input-container">
<div class="input">
<input type="text" class="expense-title-input" name="title" placeholder="Title">
<input type="number" class="expense-amount-input" name="amount" placeholder="$0">
<button type="button" class="add-expense"><img class= "plus-img" src="media/Icons/icons8-add-new-48.png" alt=""></button>
</div>
</div>
</div>
</section>
</main>
<script src="JavaScript/budget.js"></script>
</body>
</html>
I've tried to use .splice() but I can't seem to get it to work.
Your entry is an object. And entry has an id property with Date type.
Your delete function calls this:
entry_list.splice(entry.id, 1)
Javascript splice function
function takes number as argument(s).
You should find the id of element you want to delete and get its index. After that you can delete the element with splice method.
Here is how to delete:
// Find the index of object at the given list
const index = entry_list.findIndex(x => x.id === entry.id);
// Starting from index of element to delete, remove 1 element.
entry_list.splice(index, 1);

PHP Form submitting even when input is empty, and after submission doesn't stay (instead shows the php array)

I am a beginner in web development. I have a css and javascript all linked to my php form. Along with that i assigned the form action to another php file that would collect all form inputs after submission into a text file. Why is my page not staying after submission and instead shows the array? Why when there are empty inputs and the javascript alerts the form is still submitted in the php uploads? Thank you
$(document).ready(function() {
$('#defaultForm')
.bootstrapValidator({
live: 'enabled',
fields: {
'name[]': {
validators: {
notEmpty: {
message: 'The textbox field is required'
}
}
}
},
onSuccess: function(e, data) {
alert('Success');
}
});
});
function registration() {
var name = document.getElementById("name").value;
var email = document.getElementById("email").value;
var phone = document.getElementById("phone").value;
var national = document.getElementById("national").value;
var drivers = document.getElementById("drivers").value;
var dob = document.getElementById("dob").value;
var rqs = document.getElementById("rqs").value;
var confirm = document.getElementById("confirm").value;
var letters = /^[A-Za-z]+$/;
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (name == '') {
alert('Please Enter Your Name');
} else if (email == '') {
alert('Please Enter Your Email Address');
} else if (!filter.test(email)) {
alert('Invalid email');
} else if (national == '') {
alert('Please Enter Your National ID Number.');
} else if (drivers == '') {
alert('Please Enter Your Drivers License Number.');
} else if (dob == '') {
alert('Date of Birth Required');
} else if (rqs == '') {
alert('Please Choose Request Type');
} else if (confirm == '') {
alert('Please Choose Confirmation Type');
} else if (phone == '') {
alert('Please Choose Confirmation Type');
} else if (document.getElementById("phone").value.length < 11) {
alert('Phone Number minimum length is 11');
} else if (document.getElementById("phone").value.length > 11) {
alert('Phone Number max length is 12');
} else {
alert('Thank you for submitting your request. You will be redirected back to NDTS.');
window.location = "https://ndts-moi.000webhostapp.com/";
}
function clearFunc() {
document.getElementById("name").value = "";
document.getElementById("email").value = "";
document.getElementById("phone").value = "";
document.getElementById("national").value = "";
document.getElementById("drivers").value = "";
document.getElementById("dob").value = "";
document.getElementById("rqs").value = "";
document.getElementById("confirm").value = "";
}
function formvar() {
var name = document.getElementById("name").value = "";
var email = document.getElementById("email").value = "";
var phone = document.getElementById("phone").value;
var national = document.getElementById("national").value;
var drivers = document.getElementById("drivers").value;
var dob = document.getElementById("dob").value;
var rqs = document.getElementById("rqs").value;
var confirm = document.getElementById("confirm").value;
function name(name) {
var regex = (/[a-z]/);
return regex.test(name);
}
function drivers(drivers) {
var regex = /^[a-z][a-z0-9_]{4,20}$/gi;
return regex.test(drivers);
}
function email(email) {
var regex = /^([a-z0-9!#$%&'*+\-/=?^_`{|}~]+(?:\.[a-zA-Z0-9!#$%&'*+\-/=?^_`{|}~]+)*)#((?:[a-z0-9]+(?:[a-z-0-9-]*)\.)+[a-z]{2,})$/gi;
return regex.test(email);
}
function national(national) {
if (typeof national != "string") {
national = "" + national;
}
if (national.length < 16) {
return 'National ID must be 16 digits';
}
function drivers(drivers) {
if (typeof drivers != "string") {
drivers = "" + drivers;
}
if (national.length < 16) {
return 'National ID must be 16 digits';
}
function cpwd(confirmpass) {
if (cpwd != pwd_expression) {
return 'Passwords must match'
}
return true;
}
}
function phone(phone) {
var regex = /^\(?([0-9]{3})\)?[\-\.\s]?([0-9]{3})[\-\.\s]?([0-9]{4})$/g;
return regex.test(phone);
}
}
}
}
#import url('https://fonts.googleapis.com/css2?family=Poppins:wght#400;500;600&display=swap');
* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: "Poppins", sans-serif;
}
body {
display: flex;
padding: 0 10px;
min-height: 100vh;
background: #296fd8;
align-items: center;
justify-content: center;
}
::selection {
color: #fff;
background: #715543;
}
.wrapper {
width: 715px;
background: #fff;
border-radius: 5px;
box-shadow: 10px 10px 10px rgba(0, 0, 0, 0.05);
}
.wrapper header {
font-size: 22px;
font-weight: 600;
padding: 20px 30px;
border-bottom: 1px solid #ccc;
}
.wrapper form {
margin: 35px 30px;
}
.wrapper form.disabled {
pointer-events: none;
opacity: 0.7;
}
form .dbl-field {
display: flex;
margin-bottom: 25px;
justify-content: space-between;
}
.dbl-field .field {
height: 50px;
display: flex;
position: relative;
width: calc(100% / 2 - 13px);
}
.wrapper form i {
position: absolute;
top: 50%;
left: 18px;
color: #ccc;
font-size: 17px;
pointer-events: none;
transform: translateY(-50%);
}
form .field input,
form .message textarea {
width: 100%;
height: 100%;
outline: none;
padding: 0 18px 0 48px;
font-size: 16px;
border-radius: 5px;
border: 1px solid #ccc;
}
.field input::placeholder,
.message textarea::placeholder {
color: #ccc;
}
.field input:focus,
.message textarea:focus {
padding-left: 47px;
border: 2px solid #41536e;
}
.field input:focus~i,
.message textarea:focus~i {
color: #0D6EFD;
}
form .message {
position: relative;
}
form .message i {
top: 30px;
font-size: 20px;
}
form .message textarea {
min-height: 130px;
max-height: 230px;
max-width: 100%;
min-width: 100%;
padding: 15px 20px 0 48px;
}
form .message textarea::-webkit-scrollbar {
width: 0px;
}
.message textarea:focus {
padding-top: 14px;
}
form .button-area {
margin: 25px 0;
display: flex;
align-items: center;
}
.button-area button {
color: rgb(107, 83, 57);
border: none;
outline: none;
font-size: 18px;
cursor: pointer;
border-radius: 5px;
padding: 13px 25px;
background: #705643;
transition: background 0.3s ease;
}
.button-area button:hover {
background: #735a3f;
}
.button-area span {
font-size: 17px;
margin-left: 30px;
display: none;
}
#media (max-width: 600px) {
.wrapper header {
text-align: center;
}
.wrapper form {
margin: 35px 20px;
}
form .dbl-field {
flex-direction: column;
margin-bottom: 0px;
}
form .dbl-field .field {
width: 100%;
height: 45px;
margin-bottom: 20px;
}
form .message textarea {
resize: none;
}
form .button-area {
margin-top: 20px;
flex-direction: column;
}
.button-area button {
width: 100%;
padding: 11px 0;
font-size: 16px;
}
.button-area span {
margin: 20px 0 0;
text-align: center;
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>NDTS - Request Form</title>
<link rel="stylesheet" href="request.css">
<script src="javascript.js"></script>
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css" />
</head>
<body>
<div class="wrapper">
<header>NDTS Request Form</header>
<form action="upload2.php" method="post" id="form" enctype="multipart/form-data">
<div class="dbl-field">
<div class="field">
<input type="text" name="name" id="name" placeholder="Enter Your Full Name">
<i class='fas fa-user'></i>
</div>
<div class="field">
<input type="text" name="email" id="email" placeholder="Enter Your Email Address">
<i class='fas fa-envelope'></i>
</div>
</div>
<div class="dbl-field">
<div class="field">
<input type="text" name="phone" id="phone" placeholder="Enter Your Phone #">
<i class='fas fa-phone-alt'></i>
</div>
<div class="field">
<input type="text" name="national" id="national" placeholder="Enter Your National ID #">
<i class='fas fa-globe'></i>
</div>
</div>
<div class="dbl-field">
<div class="field">
<input type="text" name="drivers" id="drivers" placeholder="Enter Drivers' License #">
<i class='fas fa-globe'></i>
</div>
<div class="field">
<input type="date" name="dob" id="dob" placeholder="Enter Your Date of Birth">
<i class='fas fa-globe'></i>
</div>
</div>
<div class="message">
<label for="requests">Request Type</label>
<select name="rqs" id="rqs">
<option value="License Renewal">License Renewal</option>
<option value="Traffic Violations">Traffic Violations</option>
<option value="Replace ID">Replace National ID/Drivers License</option>
<option value="Buy/AuctionPlate">Buy/Auction Your Plate</option>
<option value="Other Requests">Other Request</option>
</select>
</div>
<div class="message">
<label for="confimation">Recieve Confimation Via</label>
<select name="confirm" id="confirm">
<option value="E-Mail">E-Mail</option>
<option value="Text Message">Text Message</option>
<option value="Phone Call">Phone Call</option>
</select>
</div>
<div class="button-area">
<input type="submit" name="send" id="send" value="Send" onclick="registration()" action="upload2.php">
<input type="reset" name="clear" id="clear" value="clear" onclick="clearFunc()">
</div>
</form>
</div>
</body>
</html>

Is there any other way to declaring addEventListener one time and using it without re-declaring?

I currently practicing HTML/CSS/DOM(JS) and more focusing on DOM right now. For now, I try to clone the instagram for studying HTML/CSS/DOM. In the DOM part(js), when I try to use event(EventListener), I am curious that "If the other project or Website need so many EventListener,Do I have to declare name.addEventListener("event name", function()) every-time? Can I declare the EventListener at the body or wrapper(div-class) and using event.target, so I don't need to be declared EventListener several times?" I am sorry if I explain so weird and messy. I tried to explain my brain storming thought. I will share my code just in case
This is HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>
Westagram!
</title>
<link rel="stylesheet" href="style/login.css" type="text/css">
<link rel="stylesheet" href="style/common.css" type="text/css">
<!-- <link rel="stylesheet" href="js/login.js"> -->
</head>
<body>
<!-- 아래 모든 div들을 포함하는 제일 상위 Container -->
<div class="wrapper">
<div class="logo">
<p class="westagram">Westagram</p>
</div>
<!-- 로그인 섹션 -->
<div class="login-container">
<div class="id">
<input type="text" id="text" placeholder="Phone number, username, or email" />
</div>
<div class="pw">
<input type="password" id="password" placeholder="Password">
</div>
<div class="bt">
<button class="login-btn">Log in
</button>
</div>
</div>
<!-- 비밀번호 찾는 섹션 -->
<div class="click">
<a class="find-password">Forgot Password</a>
</div>
</div>
<script src="js/login.js"></script>
</html>
This is CSS file
*{
padding: 0;
margin: 0;
text-decoration: none;
list-style: none;
box-sizing: border-box;
}
#font-face {
font-family: instagramFont;
src: url("../src/westagram.ttf") format("opentype");
}
.wrapper {
margin: 250px 250px 0px 250px;
padding: 30px;
display: flex;
flex-direction: column;
justify-content: space-between;
align-items: center;
border: solid 1px #D3D3D3;
width: 500px;
height: 500px;
}
.wrapper .login-container {
width: 400px;
height: 500px;
}
.wrapper .login-container .id{
margin-top: 70px;
}
#text {
width: 100%;
height: 45px;
border: solid 1px #D3D3D3;
border-radius: 5px;
padding-left: 15px;
}
#password {
width: 100%;
height: 45px;
border: solid 1px #D3D3D3;
border-radius: 5px;
padding-left: 15px;
}
.wrapper .login-container .bt .login-btn{
width: 100%;
height: 45px;
border: solid 1px #D3D3D3;
border-radius: 5px;
/*background-color: #ff000;*/
background-color: #B2DFFC;
cursor: pointer;
/*padding-left: 15px;*/
}
.wrapper .login-container .pw {
margin-top: 10px;
margin-bottom: 10px;
}
.wrapper .login-container.bt {
}
.westagram {
font-size : 60%;
font-family: instagramFont;
font-size: 5rem;
}
This is JS code
let id = document.querySelector("#text");
let password = document.querySelector("#password");
let loginButton = document.querySelector(".login-btn")
function active() {
if(id.value.length > 0 && password.value.length > 0){
loginButton.style.backgroundColor='#0095F6';
} else {
loginButton.style.backgroundColor='#B2DFFC'
}
}
id.addEventListener("keyup", active)
password.addEventListener("keyup", active)
I really appreciate your help in advance!
Can you add one event listener? Yes. It is event delegation. You use the target and you do checks to see if it is the element. Multiple ways to check if the element is the same. You can use is(), you can check a class/id/attribute or you can see if the elements match a reference
document.body.addEventListener("input", function (evt) {
const target = evt.target;
if (target.closest('#inp1, #inp2')) {
console.log(target.value);
}
});
<input type="text" id="inp1" class="loginInput" />
<input type="text" id="inp2" class="loginInput" />
document.body.addEventListener("input", function (evt) {
const target = evt.target;
if (target.classList.contains("loginInput")) {
console.log(target.value);
}
});
<input type="text" id="inp1" class="loginInput" />
<input type="text" id="inp2" class="loginInput" />
var inp1 = document.querySelector("#inp1");
var inp2 = document.querySelector("#inp2");
document.body.addEventListener("input", function(evt) {
const target = evt.target;
if (target === inp1 || target === inp2) {
console.log(target.value);
}
});
<input type="text" id="inp1" class="loginInput" />
<input type="text" id="inp2" class="loginInput" />
In the inputs are in the same container, you might not even care what input it is. Just bind the event listener to the parent. Any action inside of it will be picked up.
document.querySelector('#login').addEventListener("input", function(evt) {
const target = evt.target;
console.log(target.value);
});
<form id="login">
<input type="text" id="inp1" class="loginInput" />
<input type="text" id="inp2" class="loginInput" />
</form>
You can write a function to prevent repeating exactly the same event listeners:
function eventHandler(event, func, target ){
return target.addEventListener(event, func);
}
eventHandler("keyup", active, id);

my javascript event listener doesn't work and it still submits page - cannot read property 'addEventListener' of null [duplicate]

This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Uncaught TypeError: Cannot read property 'value' of null [duplicate]
(10 answers)
Closed last month.
I am trying to validate a contact form but none of my JavaScript is working but I guess my event listener is the problem because my page still refreshes on click of the button. It returned an error in the console
Uncaught TypeError: Cannot read property 'addEventListener' of null
const form = document.getElementById('form');
const client = document.getElementById('name');
const email = document.getElementById('email');
const message = document.getElementById('text-message');
// Show input error message
function showError(input, message) {
const formControl = input.parentElement;
formControl.className = 'form-control error';
const small = formControl.querySelector('small');
small.innerText = message;
}
// Show success outline
function showSuccess(input) {
const formControl = input.parentElement;
formControl.className = 'form-control success';
}
// Check email is valid
function checkEmail(input) {
const re = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (re.test(input.value.trim())) {
showSuccess(input);
} else {
showError(input, 'Email is not valid');
}
}
// Check required fields
function checkRequired(inputArr) {
inputArr.forEach(function(input) {
if (input.value.trim() === '') {
showError(input, `${getFieldName(input)} is required`);
} else {
showSuccess(input);
}
});
}
// Get fieldname
function getFieldName(input) {
return input.id.charAt(0).toUpperCase() + input.id.slice(1);
}
// Event listeners
form.addEventListener('submit', function(e) {
e.preventDefault();
checkRequired([client, email, message]);
checkEmail(email);
});
.container {
display: flex;
justify-content: flex-start;
flex-direction: column;
width: 30rem;
padding: 0rem 10rem; }
.container .submit-btn {
margin-top: 4rem; }
.container input {
width: 20rem;
height: 2rem;
background-color: var(--color-blue);
border: 1px solid #0652b9;
border-color: #0652b9;
border-radius: 2.5rem;
display: block;
color: #161616;
text-indent: 15px; }
.container input:focus {
outline: 0;
border-color: #ff8b2c; }
.container textarea {
width: 20rem;
height: 10rem;
background-color: var(--color-blue);
border: 1px solid #0652b9;
border-color: #0652b9;
border-radius: 1.5rem;
color: #161616;
text-indent: 15px; }
.container textarea:focus {
outline: 0;
border-color: #ff8b2c; }
.container ::placeholder {
color: #161616;
opacity: 0.5; }
.container .form-control {
position: relative; }
.container .form-control.success input {
border-color: green; }
.container .form-control.error input {
border-color: red; }
.container .form-control small {
color: red;
bottom: 0;
left: 0;
visibility: hidden; }
.container .form-control.error small {
visibility: visible; }
button {
width: 7rem;
height: 3rem;
background: #0652b9;
border-style: none;
border-radius: 2.5rem;
color: #ffffff; }
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="../css/main.css" />
</head>
<body>
<section class="container">
<form action="/" method="GET" id="form" class="form">
<div class="form-control">
<!-- <label for="name">Name</label> -->
<input type="text" id="client" placeholder="Your name">
<small>Error message</small>
</div>
<div class="form-control">
<!-- <label for="email">Email</label> -->
<input type="text" id="email" placeholder="Your email">
<small>Error message</small>
</div>
<div class="form-control">
<!-- <label for="message">Message</label> -->
<textarea name="message" id="text-message" rows="7" placeholder="Say something about your project"></textarea>
<small>Error message</small>
</div>
<button class="submit-btn" type="submit">Send message</button>
</form>
</section>
<script src="validation.js"></script>
</body>
</html>
Your selector for the variable client should be client instead of name
const form = document.getElementById('form');
const client = document.getElementById('client');
const email = document.getElementById('email');
const message = document.getElementById('text-message');
// Show input error message
function showError(input, message) {
const formControl = input.parentElement;
formControl.className = 'form-control error';
const small = formControl.querySelector('small');
small.innerText = message;
}
// Show success outline
function showSuccess(input) {
const formControl = input.parentElement;
formControl.className = 'form-control success';
}
// Check email is valid
function checkEmail(input) {
const re = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (re.test(input.value.trim())) {
showSuccess(input);
} else {
showError(input, 'Email is not valid');
}
}
// Check required fields
function checkRequired(inputArr) {
inputArr.forEach(function(input) {
if (input.value.trim() === '') {
showError(input, `${getFieldName(input)} is required`);
} else {
showSuccess(input);
}
});
}
// Get fieldname
function getFieldName(input) {
return input.id.charAt(0).toUpperCase() + input.id.slice(1);
}
// Event listeners
form.addEventListener('submit', function(e) {
e.preventDefault();
checkRequired([client, email, message]);
checkEmail(email);
});
.container {
display: flex;
justify-content: flex-start;
flex-direction: column;
width: 30rem;
padding: 0rem 10rem; }
.container .submit-btn {
margin-top: 4rem; }
.container input {
width: 20rem;
height: 2rem;
background-color: var(--color-blue);
border: 1px solid #0652b9;
border-color: #0652b9;
border-radius: 2.5rem;
display: block;
color: #161616;
text-indent: 15px; }
.container input:focus {
outline: 0;
border-color: #ff8b2c; }
.container textarea {
width: 20rem;
height: 10rem;
background-color: var(--color-blue);
border: 1px solid #0652b9;
border-color: #0652b9;
border-radius: 1.5rem;
color: #161616;
text-indent: 15px; }
.container textarea:focus {
outline: 0;
border-color: #ff8b2c; }
.container ::placeholder {
color: #161616;
opacity: 0.5; }
.container .form-control {
position: relative; }
.container .form-control.success input {
border-color: green; }
.container .form-control.error input {
border-color: red; }
.container .form-control small {
color: red;
bottom: 0;
left: 0;
visibility: hidden; }
.container .form-control.error small {
visibility: visible; }
button {
width: 7rem;
height: 3rem;
background: #0652b9;
border-style: none;
border-radius: 2.5rem;
color: #ffffff; }
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="../css/main.css" />
</head>
<body>
<section class="container">
<form action="/" method="GET" id="form" class="form">
<div class="form-control">
<!-- <label for="name">Name</label> -->
<input type="text" id="client" placeholder="Your name">
<small>Error message</small>
</div>
<div class="form-control">
<!-- <label for="email">Email</label> -->
<input type="text" id="email" placeholder="Your email">
<small>Error message</small>
</div>
<div class="form-control">
<!-- <label for="message">Message</label> -->
<textarea name="message" id="text-message" rows="7" placeholder="Say something about your project"></textarea>
<small>Error message</small>
</div>
<button class="submit-btn" type="submit">Send message</button>
</form>
</section>
<script src="validation.js"></script>
</body>
</html>
It gets submitted duo to an error is in there. Just change:
const client = document.getElementById('name');
to
const client = document.getElementById('client');

Autofocus after <input> and again after all inputs

Creating a check for entered numbers on the right div with random numbers on the left div
I don't understand how to make sure that:
after entering smth in the first input, it must focus on the second and etc.
And how after all filled inputs, it must focus again on the first input
sorry for my english
do not offer jquery, please
'use strict';
let codeNum = document.querySelectorAll('.codeNumber'),
inputNum = document.querySelectorAll('input');
function randomCode() {
codeNum.forEach(function(item) {
item.textContent = randomInteger(0, 9);
})
function randomInteger(min, max) {
// получить случайное число от (min-0.5) до (max+0.5)
let rand = min - 0.5 + Math.random() * (max - min + 1);
return Math.round(rand);
}
}
randomCode();
let new1 = [];
let new2 = [];
function checkInput() {
for (var i=0;i<codeNum.length;i++) {
new1[i] = codeNum[i].innerHTML;
new2[i] = inputNum[i].value;
}
if (JSON.stringify(new1)==JSON.stringify(new2)) {
randomCode();
}
console.log(JSON.stringify(new1));
console.log(JSON.stringify(new2));
}
for (var i=0;i<codeNum.length;i++) {
inputNum[i].addEventListener('input', checkInput)
}
#import url('https://fonts.googleapis.com/css?family=Raleway:200');
html, body {
height: 100%;
}
body {
display: flex;
align-items: center;
justify-content: space-around;
height: 100%;
background: #1D1F20;
}
.text {
width: 25px;
height: 47px;
border: 1px solid #a7a7a7;
border-radius: 4px;
background-color: #1D1F20;
outline: none;
font-size: 2.5rem;
font-family: 'Raleway';
text-align: center;
color: #fff;
vertical-align: middle;
}
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
/* display: none; <- Crashes Chrome on hover */
-webkit-appearance: none;
margin: 0; /* <-- Apparently some margin are still there even though it's hidden */
}
span {
position: absolute;
top: 6%;
}
#box {
display: flex;
align-items: center;
justify-content: space-around;
width: 400px;
height: 200px;
color: white;
font-family: 'Raleway';
font-size: 2.5rem;
}
.gradient-border {
--borderWidth: 3px;
background: #1D1F20;
position: relative;
border-radius: var(--borderWidth);
}
.gradient-border:after {
content: '';
position: absolute;
top: calc(-1 * var(--borderWidth));
left: calc(-1 * var(--borderWidth));
height: calc(100% + var(--borderWidth) * 2);
width: calc(100% + var(--borderWidth) * 2);
background: linear-gradient(60deg, #f79533, #f37055, #ef4e7b, #a166ab, #5073b8, #1098ad, #07b39b, #6fba82);
border-radius: calc(2 * var(--borderWidth));
z-index: -1;
animation: animatedgradient 3s ease alternate infinite;
background-size: 300% 300%;
}
#keyframes animatedgradient {
0% {
background-position: 0% 50%;
}
50% {
background-position: 100% 50%;
}
100% {
background-position: 0% 50%;
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Pin-Pan! by Asad</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div class="gradient-border" id="box">
<div class="numbers codeNumber">1</div>
<div class="numbers codeNumber">1</div>
<div class="numbers codeNumber">1</div>
<div class="numbers codeNumber">1</div>
</div>
<div class="gradient-border box-2" id="box">
<span>password:</span>
<div class="numbers">
<input type="number" autofocus class="text" maxlength="1" pattern="/^-?\d+\.?\d*$/" onKeyPress="if(this.value.length==1) return false;">
</div>
<div class="numbers">
<input type="number" class="text" maxlength="1" pattern="/^-?\d+\.?\d*$/" onKeyPress="if(this.value.length==1) return false;">
</div>
<div class="numbers">
<input type="number" class="text" maxlength="1" pattern="/^-?\d+\.?\d*$/" onKeyPress="if(this.value.length==1) return false;">
</div>
<div class="numbers">
<input type="number" class="text" maxlength="1" pattern="/^-?\d+\.?\d*$/" onKeyPress="if(this.value.length==1) return false;">
</div>
</div>
<script src="js/script.js"></script>
</body>
</html>
I’m not sure if I understood you question, but here’s my approach:
I’ d use recursive functions to ensure it’s called after the user did something:
function rec(num){
if (num<NumberOfElements){
let el=document.querySelectorAll(".text")[num]//select current element
el.addEventListener("input", function(){//check for input
//do something
//. /do something
num++
rec(num)//recall the recursive function (“loop again”)
}
}}
I didn’t tried the code and you’ll have to customise this for your needs.

Categories