How do I make this multi-login take me to another html within my code? (JavaScript) - javascript

I started a beginners project to learn more about JS with a multiuser ATM.
Things I'm trying to do:
3 Users that have password and balance when they log in
The login page should redirect you to the ATM site, and it will show you your balance in a pre-built calculator
I want to make the ATM work too but I first need to get the login right
Here is my code
// Login: Try limit, page change, usernames
let entryCount = 1;
let entryLimit = 3;
let users = [
{ name: "Emilio", password: "a", balance: 1000 },
{ name: "Andrea", password: "b", balance: 20000 },
{ name: "Hugo", password: "c", balance: 300000 },
];
let mainScreen = document.getElementById('login-page')
let conctentAccountScreen = document.createTextNode("account screen")
let accountScreen = document.createElement("span").setAttribute("id", "accountScreen")
// Login
let button = document.getElementById ('login');
button.onclick = function() {
let username = document.getElementById('user').value;
let password = document.getElementById('pass').value;
userExists = false
correctPassword = false
saldoExists = false
for (let i = 0; i < users.length; i++) {
if (username == users[i].username && password == users[i].password) {
userExists = true
correctPassword = true
saldoExists = true
window.location.href = "atm.html"
} else{
alert('Try again bro')
}
if (entryCount < entryLimit) {
entryCount++
alert('Username or Password are incorrect, please try again')
} else {
alert('You exceeded the number of tries')
window.location.href = "index.html"
}
}
}
#import url(https://fonts.googleapis.com/css?family=Roboto:300);
.login-page {
width: 360px;
padding: 8% 0 0;
margin: auto;
}
.form {
position: relative;
z-index: 1;
background: #FFFFFF;
max-width: 360px;
margin: 0 auto 100px;
padding: 45px;
text-align: center;
box-shadow: 0 0 20px 0 rgba(0, 0, 0, 0.2), 0 5px 5px 0 rgba(0, 0, 0, 0.24);
}
.form input {
font-family: "Roboto", sans-serif;
outline: 0;
background: #f2f2f2;
width: 100%;
border: 0;
margin: 0 0 15px;
padding: 15px;
box-sizing: border-box;font-size: 14px;
}
h1 {
font-family: "Roboto", sans-serif;
width: 100%;
border: 0;
box-sizing: border-box;font-size: 25px;
margin-bottom: 50px;
}
.form button {
font-family: "Roboto", sans-serif;
text-transform: uppercase;
outline: 0;
background: #fce205;
width: 100%;
border: 0;
padding: 15px;
color: #FFFFFF;
font-size: 14px;
-webkit-transition: all 0.3 ease;
transition: all 0.3 ease;
cursor: pointer;
}
.form button:hover,.form button:active,.form button:focus {
background: #ffbf00;
}
.form .message {
margin: 15px 0 0;
color: #b3b3b3;
font-size: 12px;
}
.form .message a {
color: #4CAF50;
text-decoration: none;
}
.form .register-form {
display: none;
}
.container {
position: relative;
z-index: 1;
max-width: 300px;
margin: 0 auto;
}
.container:before, .container:after {
content: "";
display: block;
clear: both;
}
.container .info {
margin: 50px auto;
text-align: center;
}
.container .info h1 {
margin: 0 0 15px;
padding: 0;
font-size: 36px;
font-weight: 300;color: #1a1a1a;
.container .info span {
color: #4d4d4d;
font-size: 12px;
}
.container .info span a {
color: #000000;
text-decoration: none;
}
.container .info span .fa {
color: #EF3B3A;
}
<!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">
<!-- CSS with Bootstrap -->
<link rel="stylesheet" href="css/style.css">
<script src="js/index.js"></script>
<title>ATM</title>
</head>
<body>
<div class="login-page">
<div class="form">
<h1>Welcome back to your bank, please log in.</h1>
<form class="login-form">
<input type="text" placeholder="username" id="user">
<input type="password" placeholder="password" id="pass">
<button id="login" type="button">login</button>
</form>
</div>
</div>
<!-- JAVASCRIPT -->
</body>
</html>

Dunno if this is what you need, but to change the html page via Javascript you can simply do:
location.href = '/something.html';
Or to an external site like this:
location.href = "https://stackoverflow.com/";
Also your code will alert repeatedly as you are doing alert('Try again bro') for EVERY user in the users array... also where is userExists, correctPassword and saldoExists being declarated?
Now this seems a better way of handling if user and password exists, dunno if it's what you're trying tho:
button.onclick = function() {
let username = document.getElementById('user').value;
let password = document.getElementById('pass').value;
const user = user.find(x => username == x.username && password == x.password);
if (user) {
// Do whataver you want if user is found.
location.href = "atm.html"
} else {
// Do whataver you want if user is NOT found.
alert('Try again bro');
}
}
And as so for last observation, you might like to import your Javascript file at the end of the body in the html (more information about why here: https://hackinbits.com/interview-questions/html/why-script-tags-should-be-placed-at-the-end-of-body-tag) (this is also potentially causing the error you commented)

Related

From login page it didnt redirect me to the TO-DO-List

I have here those codes. So basicly this is website with login to page and To do list but when I enter the username and password it didnt redirect me to the to do list website. The password and username in the JS code is password and username for now and it didnt work.Any ideas?
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>To-Do List</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1>To-Do List</h1>
<div id="login-container">
<h2>Login</h2>
<input type="text" id="username" placeholder="Username">
<input type="password" id="password" placeholder="Password">
<button id="login-btn">Login</button>
</div>
<div id="todo-container" style="display: none;">
<div id="input-container">
<input type="text" id="new-task" placeholder="Enter a new task">
<button id="add-btn">Add</button>
</div>
<ul id="task-list">
</ul>
</div>
<script src="script.js"></script>
</body>
</html>
CSS:
body {
font-family: Arial, sans-serif;
background-color: #f2f2f2;
}
h1 {
text-align: center;
}
#login-container {
width: 40%;
margin: 50px auto;
background-color: #fff;
padding: 20px;
border-radius: 5px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
}
#todo-container {
width: 60%;
margin: 0 auto;
background-color: #fff;
padding: 20px;
border-radius: 5px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
}
#input-container {
display: flex;
justify-content: space-between;
margin-bottom: 20px;
}
#new-task {
flex-grow: 1;
padding: 10px;
font-size: 16px;
border-radius: 5px;
border: none;
box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
}
#add-btn {
padding: 10px 20px;
font-size: 16px;
color: #fff;
background-color: #007bff;
border: none;
border-radius: 5px;
box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
cursor: pointer;
}
#task-list {
list-style: none;
margin: 0;
padding: 0;
}
.task {
margin-bottom: 10px;
padding: 10px;
font-size: 16px;
background-color: #fff;
border-radius: 5px;
box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
}
.delete-btn {
margin-left: 10px;
padding: 5px 10px;
font-size: 14px;
color: #fff;
background-color: #dc3545;
border: none;
border-radius: 5px;
box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
cursor: pointer;
}
JS
const loginForm = document.getElementById("login-container");
const todoContainer = document.getElementById("todo-container");
const usernameInput = document.getElementById("username");
const passwordInput = document.getElementById("password");
const loginBtn = document.getElementById("login-btn");
const addBtn = document.getElementById("add-btn");
const newTaskInput = document.getElementById("new-task");
const taskList = document.getElementById("task-list");
let tasks = [];
// Check if the user is logged in
if (isLoggedIn()) {
showTodo();
} else {
showLogin();
}
// Event listeners
loginBtn.addEventListener("click", handleLogin);
addBtn.addEventListener("click", handleAddTask);
taskList.addEventListener("click", handleDeleteTask);
// Functions
function handleLogin(event) {
event.preventDefault();
const username = usernameInput.value;
const password = passwordInput.value;
if (username === "Username" && password === "password") {
showTodo();
clearLoginInputs();
} else {
alert("Incorrect username or password. Please try again.");
}
}
function handleAddTask(event) {
event.preventDefault();
const taskName = newTaskInput.value;
if (taskName.trim() === "") {
alert("Please enter a task name.");
return;
}
const newTask = {
name: taskName,
completed: false,
};
tasks.push(newTask);
renderTasks();
clearNewTaskInput();
}
function handleDeleteTask(event) {
if (event.target.classList.contains("delete-btn")) {
const taskIndex = event.target.dataset.taskIndex;
tasks.splice(taskIndex, 1);
renderTasks();
}
}
function renderTasks() {
taskList.innerHTML = "";
tasks.forEach((task, index) => {
const taskElement = document.createElement("li");
taskElement.classList.add("task");
if (task.completed) {
taskElement.classList.add("completed");
}
const taskNameElement = document.createElement("span");
taskNameElement.textContent = task.name;
const deleteBtnElement = document.createElement("button");
deleteBtnElement.classList.add("delete-btn");
deleteBtnElement.textContent = "Delete";
deleteBtnElement.setAttribute("data-task-index", index);
taskElement.appendChild(taskNameElement);
taskElement.appendChild(deleteBtnElement);
taskList.appendChild(taskElement);
});
}
function clearNewTaskInput() {
newTaskInput.value = "";
}
function clearLoginInputs() {
usernameInput.value = "";
passwordInput.value = "";
}
function showLogin() {
loginForm.style.display = "block";
todoContainer.style.display = "none";
}
function showTodo() {
loginForm.style.display = "none";
todoContainer.style.display = "block";
}
function isLoggedIn() {
return localStorage.getItem("isLoggedIn") === "true";
}
I tryed a lot of things from changing little bit a code to switch to another browser.
Use console.log to find where exactly the error is instead of posting the entire code. The css was definitely not needed.
Try this:
if (username === "Username" && password === "password") {
console.log('Username and password matched');
showTodo();
clearLoginInputs();
}
If the statement is logged that would mean showTodo();clearLoginInputs(); are being executed. In this specific case, if the login inputs are being cleared, it means that the block is being called.
Now the question will be why isn't element.style.diplsay="block" not working.
Check out this link. I think it'll help
getElementById().style.display does not work
Cheers :)
I tested the same code locally and it works fine. You should check that the script file is included correctly. As a demonstration, instead of including an external script, copy and paste your script in the .html file between script tags and you will see that it works as expected.

First time deploying Chrome extension - Uncaught TypeError: Cannot read properties of null (reading 'length')

I am trying to deploy my first javascript application, which is a Chrome extension.
This simply generates random passwords and stores it with the url of current active tab.
App runs fine on local but after deploying it to Chrome, I got this error:
Uncaught TypeError: Cannot read properties of null (reading 'length')
index.js:65 (anonymous function)
I am a beginner, so any kind of criticism about my code is highly appreciated.
Thank you so much.
function render() {
*line65* **if(passwords.length === 0)** {
document.getElementById("saved-passwords-container").style.display= "none";
} else {
document.getElementById("saved-passwords-container").style.display= "unset";
}
let list = ""
**for (let i = 0; i < passwords.length; i++)** {
list += `<div class="saved-password-line"><span>${passwords[i]}</span></br></br><span class="link"><a target='_blank'href='${links[i]}'>${links[i]}</a></span></div>`
}
document.getElementById("passwords-el").innerHTML = list
}
Here is the full index.js file:
var characters = [];
for (var i=32; i<127; i++)
characters.push(String.fromCharCode(i));
for( var i = 0; i < characters.length; i++){
if ( characters[i] === '<') {
characters.splice(i, 1);
i--;
}
}
for( var i = 0; i < characters.length; i++){
if ( characters[i] === '>') {
characters.splice(i, 1);
i--;
}
}
let pw1El = document.getElementById("pw1-el")
let pw1 = ""
let passwords = []
passwords = JSON.parse(localStorage.getItem("savedPasswords"))
let links = []
links = JSON.parse(localStorage.getItem("savedLinks"))
render()
document.getElementById("char-count-el").value = 20
document.getElementById("gen-btn").addEventListener("click", function() {
var charCount = document.getElementById("char-count-el").value
pw1 = ""
for(let i = 0; i < charCount; i++) {
let randomIndex = Math.floor(Math.random() * characters.length)
pw1 += (characters[randomIndex])
}
pw1El.textContent = pw1
})
document.getElementById("save-btn").addEventListener("click", function() {
passwords.push(pw1El.innerText)
chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
links.push(tabs[0].url)
})
localStorage.setItem("savedPasswords", JSON.stringify(passwords))
localStorage.setItem("savedLinks", JSON.stringify(links))
render()
})
function render() {
**if(passwords.length === 0)** {
document.getElementById("saved-passwords-container").style.display= "none";
} else {
document.getElementById("saved-passwords-container").style.display= "unset";
}
let list = ""
**for (let i = 0; i < passwords.length; i++)** {
list += `<div class="saved-password-line"><span>${passwords[i]}</span></br></br><span class="link"><a target='_blank'href='${links[i]}'>${links[i]}</a></span></div>`
}
document.getElementById("passwords-el").innerHTML = list
}
document.getElementById("clear-btn").addEventListener("click", function() {
passwords = []
links = []
localStorage.setItem("savedPasswords", JSON.stringify(passwords))
localStorage.setItem("savedLinks", JSON.stringify(links))
render()
})
document.getElementById("copy-btn").addEventListener("click", function() {
var input = document.getElementById("pw1-el").textContent;
navigator.clipboard.writeText(input);
alert("Copied Text: " + input);
})
index.html
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="index.css">
</head>
<body>
<div class="container">
<h1>Generate a</br>random password</h1>
<p>Never use an unsecure password again.</p>
<hr>
<div>
<label for="char-count-el">Character Count:</label>
<input type="number" id="char-count-el">
<button id="gen-btn"><span>Generate password</span></button>
</div>
<div>
<label>Your Password:</label>
<div class="pw-container">
<span class="password-line" id="pw1-el">...</span>
<button class="side-btn" id="save-btn">SAVE</button>
<button class="side-btn" id="copy-btn">COPY</button>
</div>
</div>
<div id="saved-passwords-container">
<hr>
<label>Saved Passwords:</label>
<div class="pw-container">
<div id="passwords-el">...</div>
<button class="side-btn" id="clear-btn">CLEAR</button>
</div>
</div>
</div>
<script src="index.js"></script>
</body>
</html>
index.css
body {
padding: 0;
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
background-color: #ffffff;
color: white;
display: flex;
justify-content: center;
align-items: center;
}
h1::first-line {
color: white;
}
h1 {
color: #00ffaa;
margin-bottom: 5px;
line-height: 1;
}
label {
font-size: 11px;
display: block;
color: #D5D4D8;
margin-top: 10px;
}
input {
height: 38px;
border-radius: 5px;
border: none;
width: 70px;
padding: 0px 10px;
text-align: center;
background-color: #D5D4D8;
margin-right: 20px;
font-size: 14px;
}
.container {
background: #1F2937;
margin: 0;
padding: 10px 30px 40px;
width: 100%;
min-width: 500px;
box-shadow: 0px 10px 30px 10px #2640644b;
display: flex;
flex-direction: column;
}
.pw-container {
display: flex;
border-radius: 5px;
background-color: #3e4f66;
padding: 10px;
margin-top: 10px;
}
.password-line {
color: #00ffaa;
font-size: 16px;
padding: 5px 10px;
margin-top: 0px;
flex-grow: 1;
flex: 1 1 1;
min-width: 0;
word-wrap: break-word;
white-space: pre-wrap;
word-break: break-word;
}
#passwords-el {
padding-right: 30px;
flex-grow: 1;
flex: 1 1 0;
min-width: 0;
word-wrap: break-word;
white-space: pre-wrap;
word-break: break-word;
}
.saved-password-line {
color: #D5D4D8;
font-size: 14px;
padding: 10px 15px;
border-bottom: solid 1px #d5d4d814;
border-radius: 5px;
margin-bottom: 10px;
line-height: 0.9;
}
a {
color: #d5d4d872;
text-decoration: underline;
}
.side-btn {
font-size: 12px;
width: 60px;
border: none;
background: none;
color: #D5D4D8;
padding: 5px 10px;
border-radius: 5px;
justify-self: flex-end;
}
.side-btn:hover {
background-color: #ffffff28 ;
}
#gen-btn {
color: #ffffff;
background: #0EBA80;
text-transform: capitalize;
text-align: center;
width: 200px;
height: 40px;
padding: 10px 10px;
border: none;
border-radius: 5px;
margin-bottom: 10px;
margin-top: 10px;
transition: all 0.5s;
box-shadow: 0px 0px 30px 5px #0eba8135
}
#gen-btn:hover {
box-shadow: 0px 0px 30px 10px #0eba8157
}
#gen-btn span {
cursor: pointer;
display: inline-block;
position: relative;
transition: 0.5s;
}
#gen-btn span:after {
content: '\279c';
position: absolute;
opacity: 0;
top: 0;
right: -20px;
transition: 0.5s;
}
#gen-btn:hover span {
padding-right: 25px;
}
#gen-btn:hover span:after {
opacity: 1;
right: 0;
}
p {
color: #D5D4D8;
margin-top: 0px;
}
hr {
border-width: 1px 0px 0px 0px;
border-color: #95959576;
margin: 15px 0;
}
manifest.json
{
"manifest_version": 3,
"version": "1.0",
"name": "Password Generator",
"action": {
"default_popup": "index.html",
"default_icon": "icon.png"
},
"permissions": [
"tabs"
]
}
I solved it.
I understand that (please correct me if I'm wrong)
if the local storage is empty, it does not return an empty array when parsed.
Apparently, when I do:
passwords = JSON.parse(localStorage.getItem("savedPasswords"))
passwords is no longer an array.
I instead use:
passwords.push(JSON.parse(localStorage.getItem("savedPasswords")))
But that just pushes a nested array inside passwords.
So I added a for loop, and used an if statement to address the initial error:
let locSavedPasswords = localStorage.getItem("savedPasswords")
if(locSavedPasswords !== null) {
for( var i = 0; i < (JSON.parse(locSavedPasswords)).length; i++){
passwords.push(JSON.parse(locSavedPasswords)[i])
}}
Initially, savedPasswords won't exist in localStorage, so localStorage.getItem('savedPasswords') will return null.
You then do JSON.parse(null), which doesn't immediately crash because null is first coerced to a string and becomes 'null' which is then JSON-parsed and turns back to null since the string with contents null is valid JSON.
But you then do .length on it and crash.
The solution is to handle the case where the item is not yet set and handle it like it was a JSON-stringified empty array. You can do so for example using the nullish coalescing operator ??:
let passwords = JSON.parse(localStorage.getItem("savedPasswords") ?? '[]')
Or, you can keep initializing it with [] as you did before but wrap the assignment with the actual value in a condition:
let passwords = []
const json = localStorage.getItem('savedPasswords')
if (json !== null) {
passwords = JSON.parse(json)
}
Personally, what I like to do for structured data in localStorage is something like this, which also handles the case that other things like invalid JSON somehow got stored there (without bricking the application):
let passwords = []
try {
const data = JSON.parse(localStorage.getItem('savedPasswords'))
if (Array.isArray(data)) passwords = data
} catch {}

Why my javascript not work? When I change the innterHtml of an element, it didn't work

Why my javascript not work? When I change the innterHtml of an element, it didn't work?
here is my code:
html
<!DOCTYPE html>
<html><head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<title>403 没有权限!</title>
<style type="text/css" media="screen">
body {
user-select: none;
background-color: #eeeeee;
margin: 0;
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
}
.container { margin: 50px auto 40px auto; width: 600px; text-align: center; }
a { color: #4183c4; text-decoration: none; }
h1 { width: 800px; position:relative; left: -100px; letter-spacing: -1px; line-height: 60px; font-size: 160px; font-weight: 100; margin: 0px 0 50px 0; text-shadow: 0 1px 0 #fff; }
p,m { color: rgba(0, 0, 0, 0.5); margin: 20px 0; line-height: 1.6; }
#suggestions {
margin-top: 35px;
color: #ccc;
}
#suggestions a {
color: #666666;
font-weight: 200;
font-size: 14px;
margin: 0 10px;
}
</style>
</head>
<body>
<div class="container">
<br><br><br><br><br><br><br><br><br><br><br><br><br>
<h1><strong>403</strong></h1>
<p><strong>Request denied</strong></p>
<p><strong>请求被拒绝</strong></p>
<p>
If the file you are accessing is yours, please check your login information.
</p>
<m>You are now login as: </m><f id="ll"></f>
</div>
<script src="get.js"></script>
</body></html>
js
var datac
var user
function get(){
user = localStorage.getItem(datac)
if(user != null){
document.getElementById("ll").innerHtml = user
console.log(user)
}
else {
document.getElementById('ll').innerHtml = 'Please Login.'
}
}
function checklogin(){
$.getJSON('https://text-edit-api-default-rtdb.asia-southeast1.firebasedatabase.app/.json', function ( data ){
datac = data['data']['password']['localstorge']['code']
get()
})}
checklogin()
There is no any errors in console!
but if I get document.getElementById('ll').innterHtml I saw the change, but there is no changes in html!
This page is the 404 page of github page, I changed some codes.
I change innter to inner
Image
I use vscode
And chrome
It is weird you don't have errors in console. Be carfeully about the uppercase letters, the correct attribute is innerHTML instead of innerHtml
You have a syntax problem. Put innerHTML instead of innterHtml
Ref: https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML

Can't access JavaScript method in different "class"

So I'm making a calculator in JavaScript as a way to learn JavaScript. I'd like to add some sort of Object Orientated into the project.
My HTML
<!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>The Unconventional Calculator</title>
<link
href="https://fonts.googleapis.com/css?family=Roboto:400,700&display=swap"
rel="stylesheet"
/>
<link rel="stylesheet" href="assets/styles/app.css" />
</head>
<body>
<header>
<h1>The Unconventional Calculator</h1>
</header>
<section id="calculator">
<input type="number" id="input-number" />
<div id="calc-actions">
<button type="button" id="btn-add">+</button>
<button type="button" id="btn-subtract">-</button>
<button type="button" id="btn-multiply">*</button>
<button type="button" id="btn-divide">/</button>
<button type="button" id="btn-equals">=</button>
</div>
</section>
<section id="results">
<h2 id="current-calculation">0</h2>
<h2>Result: <span id="current-result">0</span></h2>
</section>
<section class="credit">
<h1>Check out my code on GitHub
<br>Type your number, press enter, repeat until you're done and then press enter.</h1>
</section>
<!-- So the site loads first then the js runs -->
<script src="assets/scripts/vendor.js"></script>
<script src="assets/scripts/app.js"> </script>
</body>
</html>
MY CSS
* {
box-sizing: border-box;
}
html {
font-family: 'Roboto', open-sans;
}
body {
margin: 0;
}
header {
background: #6d0026;
color: white;
padding: 1rem;
text-align: center;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.26);
width: 100%;
}
#results,
#calculator {
margin: 2rem auto;
width: 40rem;
max-width: 90%;
border: 1px solid #6d0026;
border-radius: 10px;
padding: 1rem;
color: #6d0026;
}
#results {
text-align: center;
}
#calculator input {
font: inherit;
font-size: 3rem;
border: 2px solid #6d0026;
width: 10rem;
padding: 0.15rem;
margin: auto;
display: block;
color: #6d0026;
text-align: center;
}
#calculator input:focus {
outline: none;
}
#calculator button {
font: inherit;
background: #6d0026;
color: white;
border: 1px solid #6d0026;
padding: 1rem;
cursor: pointer;
}
#calculator button:focus {
outline: none;
}
#calculator button:hover,
#calculator button:active {
background: #6d2d1b;
border-color: #6d2d1b;
}
#calc-actions button {
width: 4rem;
}
#calc-actions {
margin-top: 1rem;
text-align: center;
}
.credit {
margin: 70px 0 0 0;
text-align: center;
}
app.js
// Base Variables
let result = 0;
let number = 0;
//Store equation as string
let calculationDescription = "";
//Event listeners
document.querySelector("#btn-add").addEventListener('click', sumNumbs);
document.querySelector("#btn-subtract").addEventListener('click', subtractNumbs);
document.querySelector("#btn-multiply").addEventListener('click', multiplyNumbs);
document.querySelector("#btn-divide").addEventListener('click', divideNumbs);
document.querySelector("#btn-equals").addEventListener('click', equals);
document.querySelector('#input-number').addEventListener('keypress', numbersInput);
function numbersInput(e) {
if(e.key === 'Enter' && userInput !== null) {
number = e.target.value;
e.target.value = '';
calculationDescription += number + " ";
console.log(calculationDescription);
}
}
function sumNumbs() {
calculationDescription += "+ ";
}
function subtractNumbs() {
calculationDescription += "- ";
}
function multiplyNumbs() {
calculationDescription += "x ";
}
function divideNumbs() {
calculationDescription += "/ ";
}
function equals() {
let finalCalculation = calculationDescription.split(" ");
//Goes to errorHandler to remove whitespace and make array ready for equation
errorHandler.removeWhiteSpace(finalCalculation);
}
errorHandler.js
class errorHandler {
static removeWhiteSpace(arraySplit) {
return console.log(arraySplit);
}
}
vendor.js(this one isn't to important for the solution)
const userInput = document.getElementById('input-number');
const addBtn = document.getElementById('btn-add');
const subtractBtn = document.getElementById('btn-subtract');
const multiplyBtn = document.getElementById('btn-multiply');
const divideBtn = document.getElementById('btn-divide');
const equalsBtn = document.getElementById('btn-equals');
const currentResultOutput = document.getElementById('current-result');
const currentCalculationOutput = document.getElementById('current-calculation');
function outputResult(result, text) {
currentResultOutput.textContent = result;
currentCalculationOutput.textContent = text;
}
So in my equals method I'd like to send the array finalCalculation which is in the app.js class into the removeWhiteSpace method that's in my errorHandler.js
This is the error I keep getting
app.js:44 Uncaught ReferenceError: errorHandler is not defined
at HTMLButtonElement.equals (app.js:44)
I've tried turning both of them into classes and then creating a constructor with an instance variable for errorHandler to take in the array, but that doesn't seem to work.

Function error: Uncaught TypeError: undefined is not a function

Made a script that checks if: $("#password") has 9 symbols and if $("#password") = $("#confirm_password").
The problem is when I try to enable the "submit" button... What is wrong with "function submitButton()"?
$("form span").hide();
$('input[type="submit"]').attr("disabled", "true");
var samePass = false;
var eight = false;
var $password01 = $("#password");
var $password02 = $("#confirm_password")
//Why this function doesn't work?
function submitButton() {
if (samePass && eight){
$('input[type="submit"]').removeAttr('disabled');
};
};
//Checks if the pass has 8 symbles
function passwordEvent() {
if ($password01.val().length > 8) {
eight = true;
$password01.next().hide().submitButton();
} else {
$password01.next().show();
};
};
//Checks if the two passwards are the same
function passwordCheck() {
if($password02.val() !== $password01.val()) {
$password02.next().show();
} else {
samePass = true;
$password02.next().hide().submitButton();
};
};
$password01.focus(passwordEvent).keyup(passwordEvent).focus(passwordCheck).keyup(passwordCheck);
$password02.focus(passwordCheck).keyup(passwordCheck);
$("form span").hide();
$('input[type="submit"]').attr("disabled", "true");
var samePass = false;
var eight = false;
var $password01 = $("#password");
var $password02 = $("#confirm_password")
//Why this function doesn't work?
function submitButton() {
if (samePass && eight){
$('input[type="submit"]').removeAttr('disabled');
};
};
//Checks if the pass has 8 symbles
function passwordEvent() {
if ($password01.val().length > 8) {
eight = true;
$password01.next().hide().submitButton();
} else {
$password01.next().show();
};
};
//Checks if the two passwards are the same
function passwordCheck() {
if($password02.val() !== $password01.val()) {
$password02.next().show();
} else {
samePass = true;
$password02.next().hide().submitButton();
};
};
$password01.focus(passwordEvent).keyup(passwordEvent).focus(passwordCheck).keyup(passwordCheck);
$password02.focus(passwordCheck).keyup(passwordCheck);
body {
background: #384047;
font-family: sans-serif;
font-size: 10px
}
form {
background: #fff;
border-radius: 10px;
padding: 4em 4em 2em;
box-shadow: 0 0 1em #222;
max-width: 400px;
margin: 100px auto;
}
p {
margin: 0 0 3em 0;
position: relative;
}
label {
font-size: 1.6em;
font-weight:600;
color: #333;
display: block;
margin: 0 0 .5em;
}
input {
display: block;
height: 40px;
width: 100%;
box-sizing: border-box;
outline: none
}
input[type="text"],
input[type="password"] {
background: #f5f5f5;
border: 1px solid #F0F0F0;
border-radius: 5px;
font-size: 1.6em;
padding: 1em 0.5em;
}
input[type="text"]:focus,
input[type="password"]:focus {
background: #fff
}
span {
border-radius: 5px;
padding: 7px 10px;
background: #2F558E;
color: #fff;
width: 160px;
display: block; /* Needed for the width to work */
text-align: center; /* For the inner text */
position: absolute;
left: 105%;
top: 25px;
}
span:after {
content: " ";
position: absolute;
/* pointer-events: none;*/
right: 100%;
top: 50%;
/*
height: 0;
width: 0;
*/
border: solid transparent;
/* border-color: rgba(136, 183, 213, 0);*/
border-right-color: #2F558E;
border-width: 8px;
margin-top: -8px;
}
.enableSub {
background: #0099FF;
border: none;
border-radius: 5px;
color: white;
height: 50px;
box-shadow: 0 3px 0 0 #005C99;
}
.disableSub {
background: #AEAEAE;
border: none;
border-radius: 5px;
color: white;
height: 50px;
}
<!DOCTYPE html>
<html>
<head>
<title>Sign Up Form</title>
<link rel="stylesheet" href="css/style.css" type="text/css" media="screen" title="no title" charset="utf-8">
</head>
<body>
<form action="#" method="post">
<p>
<label for="username">Username</label>
<input id="username" name="username" type="text">
</p>
<p>
<label for="password">Password</label>
<input id="password" name="password" type="password">
<span>Enter a password longer than 8 characters</span>
</p>
<p>
<label for="confirm_password">Confirm Password</label>
<input id="confirm_password" name="confirm_password" type="password">
<span>Please confirm your password</span>
</p>
<p>
<input type="submit" class="disableSub" value="SUBMIT">
</p>
</form>
<script src="http://code.jquery.com/jquery-1.11.0.min.js" type="text/javascript" charset="utf-8"></script>
<script src="js/app.js" type="text/javascript" charset="utf-8"></script>
</body>
</html>
$password01.next().hide().submitButton();
et al. won't work. You instead need to do;
$password01.next().hide();
submitButton();
You've declared submitButton as a function, not a method on a jQuery object, hence you need to call it as such.
The "undefined is not a function" error appears cryptic at first, but becomes clear once understood.
Since the jQuery object returned from hide() doesn't have a submitButton property (or method), hide().submitButton returns undefined. You're then trying to call that as a function (with the ()), hence JavaScript is telling you that undefined is not a function.
As well as the above, your logic is also flawed. Namely samePass is being set to true the second you click into the password1 field (since, on focus, when they're both blank, $password02.val() === $password01.val()). That means that as soon as password is > 8 chars, both conditions will match, and your submit will be enabled.
To fix this, you should probably be setting samePass and eight to false when they don't match their criteria, and calling submitButton() in all cases to update the state
//Why this function doesn't work?
function submitButton() {
if (samePass && eight) {
$('input[type="submit"]').removeAttr('disabled');
} else {
$('input[type="submit"]').attr('disabled', "true");
}
};
//Checks if the pass has 8 symbles
function passwordEvent() {
if ($password01.val().length > 8) {
eight = true;
$password01.next().hide();
submitButton();
} else {
eight = false;
$password01.next().show();
submitButton();
};
};
//Checks if the two passwards are the same
function passwordCheck() {
if ($password02.val() !== $password01.val()) {
samePass = false;
$password02.next().show();
submitButton();
} else {
samePass = true;
$password02.next().hide();
submitButton();
};
};
... which then works; http://jsfiddle.net/9qqnqLxm/

Categories