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

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.

Related

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 {}

Problems making a button disabled/change color depending on the input. Any advice?

I've been tying to work on this code, but can't find the mistakes (and I'm guessing there are many of them) I'm making.
So far I tried it using querySelector and getElementById and I've been rewriting the functions quite a few times, but no luck so far. Any advice?
Thanks in advance.
const btnNext = document.querySelector(".btn-next");
const logIn = document.querySelector(".btn-login");
const inputMail = document.querySelector(".input-mail");
const inputPassword = document.querySelector(".input-password");
function btnLogIn() {
if (inputMail.value.length && inputPassword.value.length == 0) {
btnNext.disabled == true;
} else {
btnNext.disabled == false;
}
}
function changeColor() {
if (document.getElementById("input-mail") !== "") {
document.getElementById("btn-next").style.background = "gray";
} else {
document.getElementById("btn-next").style.background = "blue";
}
}
body{
margin: auto;
width:50%;
padding: 0;
background-color: #eeeeee;
}
form{
display: flex;
flex-direction: column;
}
.btn-next{
margin-top: .5rem;
background-color: #949aa6;
color: white;
border: none;
border-radius: 2px;
padding: 18px 119px 18px 119px;
font-size: .8rem;
font-weight: 600;
}
input{
width: 16.5rem;
height: 2rem;
box-shadow: rgba(99, 99, 99, 0.2) 0px 2px 8px 0px;
}
<body>
<form>
<p>Email</p>
<input type="email" placeholder="Email" class="input-mail" id="input-mail" onkeyup="changeColor()">
<p>Password</p>
<input type="password" placeholder="Password" class="input-password" id="input-password"><br>
</form>
<button class="btn-next" id="btn-next">NEXT</button>
</body>
const btnNext = document.querySelector(".btn-next");
const logIn = document.querySelector(".btn-login");
const inputMail = document.querySelector(".input-mail");
const inputPassword = document.querySelector(".input-password");
inputMail.addEventListener("input", verifyInput);
inputPassword.addEventListener("input", verifyInput);
function verifyInput() {
if (
inputMail.value.trim().length == 0 ||
inputPassword.value.length == 0
) {
btnNext.disabled = true;
btnNext.style.backgroundColor = "gray";
} else {
btnNext.disabled = false;
btnNext.style.backgroundColor = "blue";
}
}
body{
margin: auto;
width:50%;
padding: 0;
background-color: #eeeeee;
}
form{
display: flex;
flex-direction: column;
}
.btn-next{
margin-top: .5rem;
background-color: #949aa6;
color: white;
border: none;
border-radius: 2px;
padding: 18px 119px 18px 119px;
font-size: .8rem;
font-weight: 600;
}
input{
width: 16.5rem;
height: 2rem;
box-shadow: rgba(99, 99, 99, 0.2) 0px 2px 8px 0px;
}
<body>
<form>
<p>Email</p>
<input type="email" placeholder="Email" class="input-mail" id="input-mail">
<p>Password</p>
<input type="password" placeholder="Password" class="input-password" id="input-password"><br>
</form>
<button class="btn-next" id="btn-next" disabled>NEXT</button>
</body>
Change the following to
function btnLogIn() {
if (inputMail.value.length && inputPassword.value.length == 0) {
btnNext.disabled = true;
} else {
btnNext.disabled = false;
}
}
corrected '=' signs to change line from comparison to allocation.

How do I make this multi-login take me to another html within my code? (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)

Child div element managing

var arrlength;//////////////////////////////////////////////////////////////////
function opentextarea(borderColor) {
var arr = document.getElementsByClassName("myCustomTextarea");
arrlength=arr.length;
var goOut= 1;
Array.prototype.forEach.call(arr, function(el) {
if (el.style.backgroundColor!=='lightblue'){
goOut=0;
alert("Enter or delete the previus commnet!");
}
});
if (goOut===1){
//////////////
var comentwindow = document.getElementById("StatusID"); //StatusID
var d1 = new Date();
var d2= d1.toDateString();
var d3= d1.toLocaleTimeString();
var dateTimeUser = document.createTextNode(d2+" "+d3+" username");
//dateTimeUser.style.fontSize = "8px";
dateTimeUser.className = 'dateTimeUserClasN';
dateTimeUser.id = arrlength+"dateTimeUserID";
comentwindow.appendChild(dateTimeUser); /////////////////////////////////////////1
var input = document.createElement('textarea');
input.maxLength = 5000;
input.cols = 28;
input.rows = 5;
input.style.borderColor = borderColor;
input.className = 'myCustomTextarea';
var arr = document.getElementsByClassName("myCustomTextarea");
input.id = arrlength+"textarea";
//var comentwindow = document.getElementById("StatusID"); //StatusID
comentwindow.appendChild(input);//////////////////////////////////////////////////2
var ele = document.getElementById(arrlength+"buttonSE");
if(ele === null){
var buttonSE = document.createElement('button');
buttonSE.className = 'enterCommentBut';
buttonSE.id=arrlength+"buttonSE";
buttonSE.onclick = function() {
if(document.getElementById(arrlength+"textarea").value != ''){
document.getElementById(arrlength+"textarea").style.backgroundColor= "lightblue";
var e1 = document.getElementById('StatusID');
var e2 =(e1.children.length);
e1.removeChild(e1.children[e2-1]);
e1.removeChild(e1.children[e2-2]);
}else{
alert("It is not posible to enter empty comment.");
}
}
var SE = document.createTextNode("Enter");
buttonSE.appendChild(SE);
comentwindow.appendChild(buttonSE);/////////////////////////////////////////////3
}
var ele2 = document.getElementById(arrlength+"buttonSC");
if(ele2 === null){
var buttonSC = document.createElement('button');
buttonSC.className = 'clearCommentBut';
buttonSC.id=arrlength+"buttonSC";
buttonSC.onclick = function() {
var e1 = document.getElementById('StatusID');
var e2 =(e1.children.length);
var myNode = document.getElementById("StatusID");
while (myNode.lastChild) {
myNode.removeChild(myNode.lastChild);
}
};
var SC = document.createTextNode("Clear");
buttonSC.appendChild(SC);
comentwindow.appendChild(buttonSC);//////////////////////////////////////4
}
}
}
function createObject2(){
var e3 = document.getElementById("StatusID");
var e4 = document.getElementById("Status0ID");
var e5 = document.getElementById("Status2ID");
e3.style.display = 'block';
e4.style.display = 'block';
e5.style.display = 'block';
}
document.getElementById("clickMe2").onclick = createObject2;
function updateScroll(){
var element = document.getElementById("StatusID");
element.scrollTop = element.scrollHeight;
}
function ObjectRed(){
var borderColor= "red";
opentextarea(borderColor);
updateScroll();
}
document.getElementById("ObjectRed").onclick = ObjectRed;
function ObjectGreen(){
var borderColor= "green";
opentextarea(borderColor);
updateScroll();
}
document.getElementById("ObjectGreen").onclick = ObjectGreen;
*,
*::before,
*::after {
box-sizing: border-box;
}
div.Status0 {
position: absolute;
top: 15px;
width: 250px;
height:40px;
margin: 0;
padding: 1em;
font-size: 12px;
border: solid 1px #dfdfdf;
overflow-x: hidden;
overflow-y: visible;
background-color: white;
}
div.Status1 {
position: absolute;
top: 70px;
width: 250px;
height:700px;
margin: 0;
padding: 1em;
font-size: 12px;
border: solid 1px #dfdfdf;
overflow-x: hidden;
overflow-y: visible;
background-color: white;
}
div.Coment1{
float: left;
width: 130px;
height:100px;
margin: 0;
padding: 1em;
font-size: 12px;
/* height: 100%;
overflow: auto;*/
border: solid 1px #dfdfdf;
overflow-x: hidden;
overflow-y: visible;
background-color: yellow;
}
.content {
padding: 18px 0;
border-bottom: solid 2px #cfcfcf;
}
.myCustomTextarea {
border:0;
padding:1px;
font-size:1.0em;
font-family:"Times New Roman";
color:black;
border:solid 2px #ccc;
margin:0 0 4px;
width:215px;
height:50px;
-moz-box-shadow: inset 0 0 4px rgba(0,0,0,0.2);
-webkit-box-shadow: inset 0 0 4px rgba(0, 0, 0, 0.2);
box-shadow: inner 0 0 4px rgba(0, 0, 0, 0.2);
-webkit-border-radius: 3px;
-moz-border-radius: 3px;
border-radius: 3px;
}
.myCustomTextarea:focus {
resize: none;
border-radius: 5px;
outline: none !important;
}
.dateTimeUserClasN{
}
.startbutton{
position: absolute;
left: 270px;
top:20px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Custom </title>
</head>
<body>
<div class="Status0" id="Status0ID" style="display: none">
<input type="button" id="ObjectRed" value="Problem" />
<input type="button" id="ObjectGreen" value="Okay" />
</div>
<div class="Status2" id="Status2ID" style="display: none">
<div class="Status1" id="StatusID" style="display: none"></div>
</div>
<input class =" startbutton" type="button" id="clickMe2" value="New object2" />
<script src="js/createObject.js"></script>
<link rel="stylesheet" href="css/styleIvan.css">
</body>
</html>
I have a "div" inside main "div". Status1 inside Status2. Status1 has a time date text, textarea and two buttons (enter and cancel).
When I call opentextarea function I get this 4 elements.
Below is this code for comments managing. The problem is that when i press on "cancel" button. It deletes all. But i would like to delete only last packet of
4 elements (last Status1 div). I need Status1 to be child of Status2. So when i press on cancel to delete only last child.
I can not make this work for me, so I am asking here for help.
How to do it?

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