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

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.

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.

How to remove the last child from a certain div of a div

I'm crawling the last steps towards a project assigned for one of my classes. Basically, I have to create an implementation on web of the NIM game only using HTML/CCS/JavaScript. Tomorrow's the deadline and I'm almost done, I just have an error on when I want the AI to remove a certain quantity of elements from a pile, it just says that the pile which I'm referring is undefined, even though when i debug the code it appears to have the right info. The game board is generated dynamically based on a width variable(w) and it is created in a function at the start of the game.
I'll snippet the whole project but basically I'm gonna highlight the functions of the creation of the board (working perfectly) and where I'm having some issues on removing elements. Thanks in advance for any possible help, it's my first frontend project experience and I'm tired and clueless on what to do...
game = document.getElementsByClassName("board");
let num = document.querySelector('#board_width');
// Handle number changes
w = num.valueAsNumber;
num.addEventListener('input', function () {
let val = num.valueAsNumber;
w = val;
//console.log(typeof val, val);
});
var msz=2*w-1;
for(let k=1; k<=w; k++){
let row = document.createElement("div");
row.className = "inner_game_piece";
for(let l=1; l<=maxcols; l++){
let elem = document.createElement("div");
elem.className = "game_piece";
elem.onclick = function(){
if(canclk[k]==1){
player_move(k);
row.removeChild(row.lastElementChild);
if(winCheck()) checkmate("P");
}
}
row.appendChild(elem);
}
game[0].appendChild(row);
maxcols+=2;
}
var gm = game[0].getElementsByTagName("div");
for(let i=1; i<gm.length; i++){
if(i==pile){
var rw = gm[i].getElementsByTagName("div");
for(let j=1; j<=qnt; j++){
el[pile]--;
//having some issues here
rw.removeChild(rw.lastElementChild);
}
break;
}
}
if(winCheck()) checkmate("C");
function openLog() {
document.getElementById('logNav').style.display = 'block';
}
function closeLog() {
document.getElementById('logNav').style.display = 'none';
}
function openRules() {
document.getElementById('ruleNav').style.display = 'block';
}
function closeRules() {
document.getElementById('ruleNav').style.display = 'none';
}
var w, difficulty = 4, el = new Array(), game, execnt=0, maxcols, canclk = new Array();
window.addEventListener('load',() => {
game = document.getElementsByClassName("board");
let num = document.querySelector('#board_width');
// Handle number changes
w = num.valueAsNumber;
num.addEventListener('input', function () {
let val = num.valueAsNumber;
w = val;
//console.log(typeof val, val);
});
el[0] = 0; canclk[0] = 0;
if(w>=4) maxcols=1;
else maxcols=5;
for(let i=1; i<=w; i++){
el[i]=maxcols+i*2-2;
canclk[i]=1;
}
if(execnt==0){
var msz=2*w-1;
for(let k=1; k<=w; k++){
let row = document.createElement("div");
row.className = "inner_game_piece";
for(let l=1; l<=maxcols; l++){
let elem = document.createElement("div");
elem.className = "game_piece";
elem.onclick = function(){
if(canclk[k]==1){
player_move(k);
row.removeChild(row.lastElementChild);
if(winCheck()) checkmate("P");
}
}
row.appendChild(elem);
}
game[0].appendChild(row);
maxcols+=2;
}
execnt++;
}
});
function disenabler(pile){
for(let i=1; i<=w; i++){
if(pile==-1) canclk[i]=-1;
if(canclk[i]==2) canclk[i]--;
if(i!=pile && canclk[i]!=0 && pile!=0) canclk[i]=2;
}
}
function player_move(pile) {
if(canclk[pile]==1){
el[pile]--;
if(el[pile]==0) canclk[pile] = 0;
disenabler(pile);
if(winCheck()) checkmate("P");
}
}
function endOfTurn(){
disenabler(-1);
ai_move();
disenabler(0);
}
function winCheck(){
var activelems=0;
for(let i=1; i<=w; i++){activelems += el[i] }
console.log(activelems);
if(activelems==0) return true;
else return false;
}
function ai_move(){
if(winCheck()) checkmate("P");
var chance = document.querySelector('input[name="diff"]:checked').value;
var rn = Math.floor(Math.random() * 10) + 1;
if(rn>chance) random_play();
else winner_move();
}
function isWinning(){
var an = el[i], or = el[i], res;
if(w>1){
for(let i=2; i<=w; i++){
an = (an ^ el[i])==0;
or = (or | el[i+1])==1;
}
res = an^or;
}
else res = (an==0) ^ (or==1);
return res;
}
function random_play(){
var pile = 0, qnt=0;
while(el[pile]==0){
pile = Math.floor(Math.random() * w) + 1;
}
qnt = Math.floor(Math.random() * el[pile]) + 1;
var gm = game[0].getElementsByTagName("div");
for(let i=1; i<gm.length; i++){
if(i==pile){
var rw = gm[i].getElementsByTagName("div");
for(let j=1; j<=qnt; j++){
el[pile]--;
//having some issues here
rw.removeChild(rw.lastElementChild);
}
break;
}
}
if(winCheck()) checkmate("C");
}
function dec2bin(dec) {
var st = ((dec >>> 0).toString(2)).split("").reverse().join("");
console.log(dec, st);
return dec;
}
function winner_move(){
var pile=2, quantity=2, flag=0, counter=0;
var pair = new Array();
var pieces = new Array();
for(let i=1; i<=w; i++){
if(el[i]==0) continue;
pieces = dec2bin(el[i]);
for(let j=0; j<pieces.length; j++){
var v = pieces.charCodeAt(j)-48; var op=0;
if(v==1){
if(pair[j]%2==0){
flag = i;
counter += Math.pow(2,j);
} else{
flag = 0;
counter -= Math.pow(2,j);
}
}
pair[j]++;
}
}
pile=flag; quantity=counter;
if(quantity==0) random_play();
var gm = game[0].getElementsByTagName("div");
for(let i=1; i<gm.length; i++){
if(i==pile){
var rw = gm[i].getElementsByTagName("div");
for(let j=1; j<=quantity; j++){
el[pile]--;
rw.removeChild(rw.lastElementChild);
}
break;
}
}
if(winCheck()) checkmate("C");
}
function checkmate(winner){
if(winner=="P"){
//update win count on leaderboard table
alert("YOU WON, CONGRATULATIONS!!");
}
if(winner=="C"){
alert("Sorry, you lost :(");
}
document.location.reload();
}
body {
background-color: rgba(131, 128, 135, 1);
color: rgba(233, 255, 255, 1);
font-family: Montserrat;
overflow: auto;
}
input[type=number] {
width: 40px;
}
input[type=submit], input[type=number],
button[type=submit], button[type=button] {
background-color: rgba(131, 128, 135, 1);
color: rgba(233, 255, 255, 1);
border: none;
border-radius: 5px;
padding-top: 3px;
padding-bottom: 3px;
}
input[type=submit]:hover, button[type=submit]:hover{
color: rgba(77, 254, 209, 1);
transition: 0.5s;
}
input[type=text], input[type=password]{
background-color: rgba(51, 60, 74, 1);
color: rgba(233, 255, 255, 1);
border: 2px solid rgba(77, 254, 209, 1);
border-radius: 5px;
width: 80%;
padding: 10px 10px;
margin: 12px 0;
box-sizing: border-box;
}
h1 {
padding-left: 2%;
}
h2 {
font-size: 25px;
color: rgba(77, 254, 209, 1);
}
p {
text-align: justify;
padding-left: 3%;
}
ul{
text-align: left;
}
.white_hr {
width: 50%;
align-self: center;
border-top: 5px solid rgba(233, 255, 255, 1);;
border-radius: 5px;
}
.highlight {
color:rgba(77, 254, 209, 1);
font-weight: bold;
font-style: italic;
}
.header {
background-color: rgba(51, 60, 74, 1);
border-radius: 30px;
height: 60px;
width: auto;
position: relative;
}
.header h1 {
font-size: 30px;
float: left;
padding-left: 20px;
position: absolute;
top: 50%;
margin-top: -16px;
}
.header h3 {
color: rgba(77, 254, 209, 1);
float: right;
padding-right: 20px;
}
.header h3:hover {
transition: 0.5s;
color: rgba(233, 255, 255, 1);
cursor: pointer;
}
.container {
text-align: center;
height: 700px;
width: 98%;
display: flex;
justify-content: space-between;
padding-top: 2%;
padding-right: 5px;
padding-left: 5px;
padding-bottom: 30px;
}
.container hr {
width: 80%;
border-top: 5px solid rgba(77, 254, 209, 1);
border-radius: 5px;
}
.container h2:hover {
transition: 0.5s;
color: rgba(233, 255, 255, 1);
cursor: pointer;
}
.container div {
align-items: center;
padding-top: 1%;
}
.inner_game_piece {
display: flex;
flex-direction: row;
align-items: center;
justify-content: left;
max-width: 750px;
margin: 0 auto;
flex-wrap: wrap;
}
.game_piece{
width:45px;
height:35px;
border-radius: 50px;
margin:5px;
background-color: rgba(51, 60, 74, 1);
}
.settings, .game, .leaderboard {
display: inline-block;
vertical-align: top;
}
.settings, .leaderboard {
background-color: rgba(51, 60, 74, 1);
border-radius: 20px;
height: auto;
width: 20%;
}
.game {
border: 5px solid rgba(51, 60, 74, 1);
border-radius: 20px;
height: auto;
width: 55%;
}
.small_size {
font-size: 16px;
font-weight: bold;
color: rgba(229, 202, 202, 1);
}
.logNav, .ruleNav {
display: none;
position: fixed;
z-index: 1;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
background-color: rgba(131, 128, 135, 1);
background-color: rgba(131, 128, 135, 0.5);
padding: 20% 0 0 0;
}
.log_container, .rule_container{
background-color: rgba(51, 60, 74, 1);
margin: 5% auto 15% auto;
border: none;
border-radius: 10px;
width: 80%;
height: auto;
padding: 2% 2% 2% 0;
}
.closex {
float: right;
color: rgba(77, 254, 209, 1);
font-weight: bold;
font-size: 30px;
cursor: pointer;
}
.closex:hover {
transition: 0.5s;
color: rgba(233, 255, 255, 1);
}
.cancelbtn {
margin: 10px 0;
width: auto;
height: auto;
padding: 80% 10px;
}
.about_title, .rule_title {
font-size: 30px;
text-align: left;
color:rgba(77, 254, 209, 1);
}
.logs {
background-color: rgba(51, 60, 74, 1);
border-radius: 15px;
width: 100%;
height: 150px;
}
.logs h4 {
font-size: 20px;
color: rgba(77, 254, 209, 1);
padding: 2% 2% 0 2%;
}
.logs_box {
background-color:rgba(131, 128, 135, 0.5);
overflow: auto;
}
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width:device-width, initial-scale=1.0">
<link rel="stylesheet" href="styles.css">
<script src="script.js"></script>
<title>N I M</title>
</head>
<body>
<div class="header">
<h1>N I M</h1>
<h3 onclick="openLog()">Log in</h3>
</div>
<!-- Login prompt-->
<div id="logNav" class="logNav">
<form>
<div class="log_container">
<div class="log_auth">
<span class="closex" onclick="closeLog()" title="close Login">×</span><br>
<label for="username"><b>Username</b></label><br>
<input type="text" id="username" placeholder="Enter Username" name="username" required><br>
<label for="password"><b>Password</b></label><br>
<input type="password" id="password" placeholder="Enter Password" name="password" required><br>
<button type="submit">Login</button>
<label>
<input type="checkbox" name="guest"><b>Stay as guest</b>
</label><br>
</div>
</div>
</form>
</div>
<div id="main" class="main">
<div class="container">
<!-- Settings Tab -->
<div class="settings">
<h2>Settings</h2>
<hr>
<form>
<div>
<label for="board_width"><b>Board Size</b></label><br>
<input type="number" id="board_width" name="board_width" value="1">
</div>
<hr>
<div>
<h2>Game Mode</h2>
<label for="single_player" class="small_size">SinglePlayer</label>
<input type="radio" id="single_player" name="choose_mode"><br>
<label for="multi_player" class="small_size">MultiPlayer</label>
<input type="radio" id="multi_player" name="choose_mode"><br>
</div>
<hr>
<div>
<h2>Difficulty</h2>
<label for="easy_diff" class="small_size">Easy</label>
<input type="radio" id="easy_diff" value=1 name="diff"><br>
<label for="medium_diff" class="small_size">Medium</label>
<input type="radio" id="medium_diff" value=4 name="diff"><br>
<label for="hard_diff" class="small_size">Hard</label>
<input type="radio" id="hard_diff" value=8 name="diff"><br>
<label for="extreme_diff" class="small_size">Extreme</label>
<input type="radio" id="extreme_diff" value=10 name="diff"><br>
</div>
<hr>
<h2 onclick="openRules()">Rules/About</h2>
<div id="ruleNav" class="ruleNav">
<div class="rule_container">
<span class="closex" onclick="closeRules()" title="close Rules/About">×</span><br>
<h1 class="about_title"><u>What is the NIM game?</u></h1>
<p> -> Nim is a mathematical game of <span class="highlight">strategy</span> in which 2 players take turns
to remove objects from distinct piles. In each turn, the player must choose one pile
and remove at least 1 object from that pile. <b>To win the game you must be the last
player to remove the final set of objects!</b>
</p>
<h1 class="rule_title"><u>What are the Rules?</u></h1>
<ul>
<li>In each turn, the player must remove 1 or more object from an unique horizontal pile;</li>
<li>The player cannot remove 2 or more objects from different piles in the same turn;</li>
<li>Depending on the settings defined:</li>
<li style="list-style: none;"><ul>
<li>The amount of piles can be defined by the user;</li>
<li>The user can also choose who goes first (player 1 or player 2);</li>
<li>Game can be player online <b>(work in progress)</b> or with a robot;</li>
<li>If <b>SinglePlayer</b> was selected, the player can choose the desired difficulty;</li>
</ul></li>
<li>In case of a foul play, the game will not register the move, and will wait for a proper move;</li>
<li>Logs about the state of the game are shown below the game area <b>(for foul plays, winning, and play information)</b>;</li>
</ul>
</div>
</div>
</form>
</div>
<div class="game">
<h2>Game Board</h2>
<hr>
<div class="board"></div>
<script src="script.js"></script>
<hr>
<div class="game_btn">
<button type="reset" onClick="window.location.reload()">New Game / Reset</button>
<button type="button" onClick="endOfTurn()">End Turn</button>
</div>
</div>
<div class="leaderboard">
<h2>Leaderboards</h2>
<hr>
<div class="result_box">
<p>- theres no results registered adfsdfadfasdfsfd</p>
</div>
</div>
</div>
<div class="logs">
<h4>Logs</h4>
<div class="log_box">
<p>lobby: Welcome to NIM!</p>
</div>
</div>
</div>
</body>
</html>
Try to replace
var rw = gm[i].querySelector("div"); <=== changed
for(let j=1; j<=qnt; j++){
el[pile]--;
//having some issues here
rw.removeChild(rw.lastElementChild);
}
break;
getElementsByTagName returns HTMLCollection.
There is no method removeChild in HTMLCollection.
https://developer.mozilla.org/en-US/docs/Web/API/HTMLCollection
Keep your code consistent - naming is 80% of coding (game and msz), 10% is consistency (winCheck and ai_move). The rest is describe in API's documentation ;)
Well done!

If..,else.. in javascript

I am trying to solve my problem with if-else in Javascript.
I would highly appreciate your help.
I wanted to filter the name via gender, also safe the keys - woman / man to local storage.
But I can not find out how to make if-else clause.
Can someone help me?
There is also the link:
https://drive.google.com/file/d/1RNJxbiU_DsFTCqGJWgxpepCgdOhGuzIj/view?usp=sharing
Thanks a lot, it means world to me, I am new here. :-)
$(document).ready(function() {
function displayName() {
let safeNameVal = localStorage.getItem('woman');
let safeName;
if (safeNameVal) {
safeName = JSON.parse(safeNameVal);
} else {
safeName = [];
}
//find list
let nameUl = $('#list_2');
nameUl.empty(); //.html('')
//making list
$.each(safeName, function(key, name) {
let nameLi = $('<li></li>');
nameLi.text(name);
//remove link
let jmenoRemoveLink = $('x');
jmenoRemoveLink.click(function(e) {
e.preventDefault();
//name
let safeNameVal = localStorage.getItem('woman');
let safeName;
if (safeNameVal) {
safeName = JSON.parse(safeNameVal);
} else {
safeName = [];
}
//remove
safeName.splice(key, 1);
//safe name
localStorage.setItem('woman', JSON.stringify(safeName));
//display name
displayName();
});
nameLi.append(jmenoRemoveLink);
nameUl.append(nameLi);
});
}
$('#formular').submit(function(e) {
e.preventDefault();
let zadaneJmeno = $('#name').val();
if (zadaneJmeno) {
//safe
let safeNameVal = localStorage.getItem('woman');
let safeName;
if (safeNameVal) {
safeName = JSON.parse(safeNameVal);
} else {
safeName = [];
}
safeName.push(zadaneJmeno);
localStorage.setItem('woman', JSON.stringify(safeName)); /// ["Tom"]
//list
displayName();
$('#name').val('');
} else {
// alert
alert('please enter the name"');
$('#name').focus();
}
});
$('#removeAll').click(function() {
localStorage.setItem('woman', '[]'); ///localStorage.setItem('woman', JSON.stringify([]));
displayName();
});
displayName();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="formular">
<label for="name">Enter the name</label>
<input type="text" id="name" required />
<label for="section">Gender</label>
<select name="selectSection" id="section" required>
<option value="">---</option>
<option value="man" id="man">man</option>
<option value="woman" id="woman">woman</option>
</select>
<input type="submit" value="add" />
</form>
<button id="removeAll">Remove</button>
<div id="man_div">
<h1>man:</h1>
<ul id="list"></ul>
</div>
<div id="woman_div">
<h1>woman:</h1>
<ul id="list_2"></ul>
</div>
I made a number of changes to your script, do note that as I am solving your problem, I removed the 'x' function on click because it is too verbose to read while solving your problem, do add it back later, and make sure you remove from the correct localStorage.
$(document).ready(function () {
function displayName() {
//Separate the local storage into man and woman keys
let manSafeNameVal = localStorage.getItem('man');
let manSafeName;
let womanSafeNameVal = localStorage.getItem('woman');
let womanSafeName
if (manSafeNameVal) {
manSafeName = JSON.parse(manSafeNameVal);
} else {
manSafeName = [];
}
if (womanSafeNameVal) {
womanSafeName = JSON.parse(womanSafeNameVal);
} else {
womanSafeName = [];
}
//find list
//Use list and list_2 to display
let manUl = $('#list');
let womanUl = $('#list_2');
manUl.empty(); //.html('')
womanUl.empty();
//list for man
$.each(manSafeName, function (key, name) {
let nameLi = $('<li></li>');
nameLi.text(name);
//do add back your 'x' remove here, because it is too verbose to read when I am trying to read the code
manUl.append(nameLi);
});
//list for woman
$.each(womanSafeName, function (key, name) {
let nameLi = $('<li></li>');
nameLi.text(name);
//Also here, the 'x' for woman list
womanUl.append(nameLi);
});
}
$('#formular').submit(function (e) {
e.preventDefault();
let zadaneJmeno = $('#name').val();
//get the selected gender, either man or woman
let gender = $('#section').val();
console.log(gender);
console.log(zadaneJmeno);
if (zadaneJmeno && gender !== "") {
//safe into the localStorage of selected gender
let safeNameVal = localStorage.getItem(gender);
let safeName;
if (safeNameVal) {
safeName = JSON.parse(safeNameVal);
} else {
safeName = [];
}
safeName.push(zadaneJmeno);
localStorage.setItem(gender, JSON.stringify(safeName));/// ["Tom"]
//list
displayName();
$('#name').val('');
} else {
// alert
alert('please enter the name"');
$('#name').focus();
}
});
$('#removeAll').click(function () {
localStorage.setItem('woman', '[]'); ///localStorage.setItem('woman', JSON.stringify([]));
displayName();
});
displayName();
});
const katText = document.getElementById('txtKategorie');
const oText=document.querySelector('input[homework="homework"]');
// selektor tlačítka uložit úkol
const oBttn=document.querySelector('input[type="submit"]');
// selektor tlačítka na odstranění všech úkolů z kategorie
const oDelete=document.querySelector('button#removeAll');
const createlist=function(){
let parent=document.getElementById('lists');
Object.keys(localStorage).forEach(function (key) {
let category = key;
let div = document.createElement('div');
div.id = category;
let h1 = document.createElement('h1');
h1.textContent = category;
let ul = document.createElement('ul');
div.appendChild(h1);
div.appendChild(ul);
div.onclick = oznacDiv;
parent.appendChild(div);
});
parent.querySelectorAll('div').forEach( div=>{
div.addEventListener('click',function(e){
// odstranění určité položky
if( e.target!=e.currentTarget && e.target.tagName=='A') deleteitem( e );
});
// při načtení stránky načíst úkoly z localStorage a vytvoření listu
// podmmínka -- pokud není úložiště prázdné
let store=div.id;
if( localStorage.getItem(store)!=null )JSON.parse( localStorage.getItem( store ) ).forEach( homework=>{
addlistitem(homework,store);
})
});
}
//na klik oznaci div
function oznacDiv() {
if (oBttn.disabled) oBttn.disabled = false;
document.querySelectorAll('div.active').forEach(div => {
div.classList.remove('active')
});
document.querySelector('div#' + this.id).classList.add('active')
}
const clearstoreitems=function(category){
localStorage.setItem( category, JSON.stringify([]) );
document.querySelector( 'div#' + category ).querySelector('ul').innerHTML='';
};
const deleteitem=function(e){
let parent=e.target.parentNode;
let homework=parent.dataset.homework;
let category=parent.dataset.category;
parent.parentNode.removeChild(parent);
let data=JSON.parse(localStorage.getItem(category));
if( data!=null )data.splice(data.indexOf(homework),1);
localStorage.setItem(category,JSON.stringify(data));
};
const addlistitem=function(homework,category){
let p=document.createElement('button');
p.innerHTML=' Uprava';
p.onclick =function(){
editWorking(li);
}
let a=document.createElement('a');
a.href='#';
a.innerHTML=' Hotovo';
let li=document.createElement('li');
li.value=homework;
li.textContent=homework;
li.dataset.homework=homework;
li.dataset.category=category;
li.appendChild( a );
li.appendChild(p);
document.querySelector( 'div#' + category ).querySelector('ul').appendChild( li );
};
function editWorking(e){
let editValue = prompt('Přejete si upravit úkol?', e.firstChild.nodeValue);
e.firstChild.nodeValue = editValue;
let parent=e.parentNode;
let homework=parent.dataset.homework;
let category=parent.dataset.category;
addlistitem(editValue,category);
addstoreitem(editValue,category);
}
const addstoreitem=function(homework,category){
let data=localStorage.getItem( category );
if( data!=null ){
let json=JSON.parse( data );
json.push(homework);
data=JSON.stringify(json);
}
else
{
data=JSON.stringify([homework]);
}
localStorage.setItem( category, data );
};
//prida novej div s kategorii a poznamkou
const addNewItemList = function () {
let parent = document.getElementById('lists');
let category = katText.value;
let div = document.createElement('div');
div.id = category;
let h1 = document.createElement('h1');
h1.textContent = category;
let ul = document.createElement('ul');
div.appendChild(h1);
div.appendChild(ul);
div.onclick = oznacDiv;
parent.appendChild(div);
parent.querySelectorAll('div').forEach(div => {
div.addEventListener('click', function (e) {
// odstranění určité položky
if (e.target != e.currentTarget && e.target.tagName == 'A') deleteitem(e);
});
// při načtení stránky načíst úkoly z localStorage a vytvoření listu
// podmmínka -- pokud není úložiště prázdné
let store = div.id;
if (localStorage.getItem(store) != null) JSON.parse(localStorage.getItem(store)).forEach(homework => {
addlistitem(homework, store);
})
});
}
oBttn.addEventListener('click',function(e){
e.preventDefault();
if (oText.value != '') {
if (katText.value != '') {
if (document.querySelector('div#' + katText.value) == null) {
addNewItemList()
}
addlistitem(oText.value, katText.value);
addstoreitem(oText.value, katText.value);
oText.value = '';
return true;
} else {
alert('Zadejte kategorii prosím...');
}
} else {
alert('Zadejte úkol prosím...');
}
});
// vymazat, resetovat pole
oDelete.addEventListener('click', function (e) {
document.querySelectorAll('div.active').forEach(div => {
//clearstoreitems(document.querySelectorAll('div.active').id);
clearstoreitems(div.id);
//div.classList.remove('active')
});
});
createlist();
#charset "UTF-8";
/* CSS Document */
#import url('https://fonts.googleapis.com/css2?family=Poppins:wght#100;200;300;400;500;600;700;800;900&display=swap');
*{
padding: 100;
margin: 100;
box-sizing: border-box;
font-family: 'Poppins', sans-serif;
}
/**styly pro tělo celé aplikace **/
body{
background: rgb(131,58,180);
background: linear-gradient(90deg, rgba(131,58,180,1) 0%, rgba(253,29,29,1) 50%, rgba(252,176,69,1) 100%);
/* background: linear-gradient(139deg, rgba(193,62,62,1) 0%, rgba(230,179,50,1) 100%);
background-image: url("pozadi.png");*/
overflow-x: hidden;
background-repeat: no-repeat;
background-size: cover;
background-position: center;
background-attachment: fixed;
height: 100%;
}
.weather{
width: 100%;
margin: 20px;
padding: 30px;
}
/** pomohla jsem si tady https://the-echoplex.net/flexyboxes/ **/
/**
.flex-container {
display: -ms-flexbox;
display: -webkit-flex;
display: flex;
-webkit-flex-direction: column;
-ms-flex-direction: column;
flex-direction: column;
-webkit-flex-wrap: nowrap;
-ms-flex-wrap: nowrap;
flex-wrap: nowrap;
-webkit-justify-content: flex-start;
-ms-flex-pack: start;
justify-content: flex-start;
-webkit-align-content: center;
-ms-flex-line-pack: center;
align-content: center;
-webkit-align-items: center;
-ms-flex-align: center;
align-items: center;
}
.flex-item:nth-child(1) {
-webkit-order: 0;
-ms-flex-order: 0;
order: 0;
-webkit-flex: 0 1 auto;
-ms-flex: 0 1 auto;
flex: 0 1 auto;
-webkit-align-self: auto;
-ms-flex-item-align: auto;
align-self: auto;
}
.flex-item:nth-child(2) {
-webkit-order: 0;
-ms-flex-order: 0;
order: 0;
-webkit-flex: 0 100 auto;
-ms-flex: 0 100 auto;
flex: 0 100 auto;
-webkit-align-self: auto;
-ms-flex-item-align: auto;
align-self: auto;
}
**/
/**nadpis aplikace **/
#nadpis {
/** margin: auto;
width: 50%;
padding: 5px; **/
text-align: center;
font-size: 40px;
}
.predpoved {
/** width: 30%; **/
border-radius: 15px 50px;
border:4px solid white;
background: black;
-webkit-box-shadow: 7px 8px 6px 0px rgba(0,0,0,0.52);
box-shadow: 7px 8px 6px 0px rgba(0,0,0,0.52);
margin:0 auto;
height: 10%;
width:60%;
padding: 0 auto;
}
.nadpis_1{
font-size: 50px;
color:white;
font:bold;
}
label{
color:white;
font:oblique;
text-transform:inherit;
}
#lists > div{
padding:1rem;
margin:1rem auto;
border-radius: 15px 50px;
border:4px solid white;
margin-left: 30px;
margin-right: 30px;
-webkit-box-shadow: 7px 8px 6px 0px rgba(0,0,0,0.52);
box-shadow: 7px 8px 6px 0px rgba(0,0,0,0.52);
}
.active{
background: linear-gradient(90deg, rgba(252,176,69,1) 0%, rgba(253,29,29,1) 50%, rgba(131,58,180,1)100%);
}
h1{
text-transform:capitalize;
color:white;
}
ul{
list-style: square;
}
ul li{
color:white;
margin-top: 40px;
font-size: 20px;
}
ul a {
color:white;
font:oblique;
padding: 10px;
margin:10px;
margin-left:100px;
border-radius: 15px ;
border:1px solid white;
text-decoration: none;
text-transform: uppercase;
}
ul a:hover {
color:white;
font:oblique;
background:rgba(252,176,69,1);
padding: 10px;
margin:10px;
margin-left:100px;
border:1px solid white;
text-decoration: none;
text-transform: uppercase;
}
form{
color: white;
padding: 20px;
width: 600px;
margin: 0 auto;
height: auto;
}
#removeAll{
color:white;
font:oblique;
background: black;
border-radius: 15px ;
border:1px solid white;
text-decoration: none;
text-transform: uppercase;
margin: 0 auto;
height: auto;
padding:10px;
margin-left: 30px;
margin-right: 30px;
}
#removeAll:hover {
color:white;
font:oblique;
background: red;
border:1px solid white;
text-decoration: none;
text-transform: uppercase;
padding:10px;
margin: 0 auto;
height: auto;
margin-left: 30px;
margin-right: 30px;
}
#refresh{
color:white;
font:oblique;
background: black;
border-radius: 15px ;
border:1px solid white;
text-decoration: none;
text-transform: uppercase;
margin: 0 auto;
height: auto;
padding: 10px;
}
#refresh:hover {
color:white;
font:oblique;
background: red;
border:1px solid white;
text-decoration: none;
text-transform: uppercase;
padding:10px;
margin: 0 auto;
height: auto;
}
#safe{
color:white;
font:oblique;
background: black;
border-radius: 15px ;
border:1px solid white;
text-decoration: none;
text-transform: uppercase;
margin: 0 auto;
height: auto;
padding: 10px;
}
#safe:hover {
color:white;
font:oblique;
background: red;
border:1px solid white;
text-decoration: none;
text-transform: uppercase;
padding:10px;
margin: 0 auto;
height: auto;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Deadline</title>
<link rel="stylesheet" href="style.css">
<script src="//code.jquery.com/jquery-3.3.1.min.js"></script>
</head>
<body>
<div class="flex-container">
<div id="nadpis">
<h1>Deadline</h1>
<form>
<label for="txtHomework">Your homework.. </label>
<input type="text" id="txtHomework" homework="homework" required />
<label for="txtKategorie">Category</label>
<input type="text" id="txtKategorie" kategorie="valKategorie" required />
<!--<select name="selectSection" required>
<option selected hidden disabled>---</option>
<option value="škola">Škola</option>
<option value="Práce">Práce</option>
<option value="Doma">Doma</option>
<option value="Jiné">Jiné</option>
</select>-->
<!--</label>-->
<!-- tlačítko uložit je nedostupné dokud nevybereme kategorii a nezapíšeme úkol -->
<input id ="safe" type="submit" value="Uložit" />
</form>
<div id="lists"></div>
<button id="removeAll">Vyčistit kategorii</button>
I know you already have a solution but I offer an alternative, in vanilla Javascript rather than jQuery, that splits the names according to gender - assigns them to individual areas in localStorage based upon gender and has the functionality to remove individual items from the store. Any items stored in any of the generated stores will be used to populate the HTML lists on page load. I don't use jQuery which is why I wrote this in plain js - no doubt you can cherrypick things from it that might be useful - I hope that it is useful anyway.
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title>Gender splitter</title>
<style>
#lists > div{
padding:1rem;
margin:1rem auto;
border:1px dotted gray;
}
.active{
background:whitesmoke
}
h1{text-transform:capitalize}
</style>
</head>
<body>
<form>
<label>Enter the name
<input type='text' name='name' required />
</label>
<label>Gender
<select name='selectSection' required>
<option selected hidden disabled>---
<option value='male'>Male
<option value='female'>Female
<option value='teapot'>Teapot
<option value='crocodile'>Crocodile
</select>
</label>
<!-- initially disabled to prevent adding when no gender is selected -->
<input type='submit' value='add' disabled />
</form>
<button id='removeAll'>Remove</button>
<div id='lists'></div>
<script>
const oSelect=document.querySelector('select[name="selectSection"]');
const oText=document.querySelector('input[name="name"]');
const oBttn=document.querySelector('input[type="submit"]');
const oDelete=document.querySelector('button#removeAll');
// generate the necessary HTML nodes to display names/genders based
// upon the options in the select menu.
const createlist=function(){
let parent=document.getElementById('lists');
oSelect.querySelectorAll('option').forEach( option=>{
if( option.value !== oSelect.childNodes[1].value ){
let gender=option.value;
let div=document.createElement('div');
div.id=gender;
let h1=document.createElement('h1');
h1.textContent=gender;
let ul=document.createElement('ul');
div.appendChild(h1);
div.appendChild(ul);
parent.appendChild( div );
}
});
parent.querySelectorAll('div').forEach( div=>{
div.addEventListener('click',function(e){
// delete specific item from the store
if( e.target!=e.currentTarget && e.target.tagName=='A') deleteitem( e );
});
// load any names from the store on page load and recreate the lists
let store=div.id;
if( localStorage.getItem(store)!=null )JSON.parse( localStorage.getItem( store ) ).forEach( name=>{
addlistitem(name,store);
})
});
}
// erase store content by gender and clear html list display
const clearstoreitems=function(gender){
localStorage.setItem( gender, JSON.stringify([]) );
document.querySelector( 'div#' + gender ).querySelector('ul').innerHTML='';
};
// delete specific item from particular store
const deleteitem=function(e){
let parent=e.target.parentNode;
let name=parent.dataset.name;
let gender=parent.dataset.gender;
parent.parentNode.removeChild(parent);
let data=JSON.parse(localStorage.getItem(gender));
if( data!=null )data.splice(data.indexOf(name),1);
localStorage.setItem(gender,JSON.stringify(data));
};
// add new item to HTML list based upon gender
const addlistitem=function(name,gender){
let a=document.createElement('a');
a.href='#';
a.innerHTML='X';
let li=document.createElement('li');
li.value=name;
li.textContent=name;
li.dataset.name=name;
li.dataset.gender=gender;
li.appendChild( a );
document.querySelector( 'div#' + gender ).querySelector('ul').appendChild( li );
};
// add new name to the localStorage in gender specific named store
const addstoreitem=function(name,gender){
let data=localStorage.getItem( gender );
if( data!=null ){
let json=JSON.parse( data );
json.push(name);
data=JSON.stringify(json);
} else { data=JSON.stringify([name]); }
localStorage.setItem( gender, data );
};
// Add new item listener
oBttn.addEventListener('click',function(e){
e.preventDefault();
if( oText.value!='' ){
addlistitem(oText.value,oSelect.value);
addstoreitem(oText.value,oSelect.value);
oText.value='';
return true;
}
alert('Name please...');
});
oSelect.addEventListener('change',function(e){
// ensure the "Add" button is enabled
if( oBttn.disabled )oBttn.disabled=false;
document.querySelectorAll('div.active').forEach( div=>{
div.classList.remove('active')
});
// assign a class to visually identify which gender is selected
document.querySelector( 'div#' + this.value ).classList.add('active')
});
// erase this entire store - reset to empty array
oDelete.addEventListener('click',function(e){
clearstoreitems(oSelect.value);
});
createlist();
</script>
</body>
</html>

Adding a square root function to a calc using js

So, I made a calculator, and I want to add a square root function, but I know there is no already made function that finds the square root of numbers. So what elements can I combine to find the square root of a number?
const screen = document.querySelector("#screen");
const clearButton = document.querySelector("#clear");
const equalsButton = document.querySelector("#equals");
const decimalButton = document.querySelector("#decimal");
let isFloat = false;
let signOn = false;
let firstNumber = "";
let operator = "";
let secondNumber = "";
let result = "";
const allClear = () => {
isFloat = false;
signOn = false;
firstNumber = "";
operator = "";
secondNumber = "";
result = "";
screen.value = "0";
};
const calculate = () => {
if (operator && result === "" && ![" ", "+", "-", "."].includes(screen.value[screen.value.length - 1])) {
secondNumber = screen.value.substring(firstNumber.length + 3);
switch (operator) {
case "+":
result = Number((Number(firstNumber) + Number(secondNumber)).toFixed(3));
break;
case "-":
result = Number((Number(firstNumber) - Number(secondNumber)).toFixed(3));
break;
case "*":
result = Number((Number(firstNumber) * Number(secondNumber)).toFixed(3));
break;
case "/":
result = Number((Number(firstNumber) / Number(secondNumber)).toFixed(3));
break;
default:
}
screen.value = result;
}
};
clear.addEventListener("click", allClear);
document.querySelectorAll(".number").forEach((numberButton) => {
numberButton.addEventListener("click", () => {
if (screen.value === "0") {
screen.value = numberButton.textContent;
} else if ([" 0", "+0", "-0"].includes(screen.value.substring(screen.value.length - 2))
&& numberButton.textContent === "0") {
} else if ([" 0", "+0", "-0"].includes(screen.value.substring(screen.value.length - 2))
&& numberButton.textContent !== "0") {
screen.value = screen.value.substring(0, screen.value.length - 1) + numberButton.textContent;
} else if (result || result === 0) {
allClear();
screen.value = numberButton.textContent;
} else {
screen.value += numberButton.textContent;
}
});
});
decimalButton.addEventListener("click", () => {
if (result || result === 0) {
allClear();
isFloat = true;
screen.value += ".";
} else if (!isFloat) {
isFloat = true;
if ([" ", "+", "-"].includes(screen.value[screen.value.length - 1])) {
screen.value += "0.";
} else {
screen.value += ".";
}
}
});
document.querySelectorAll(".operator").forEach((operatorButton) => {
operatorButton.addEventListener("click", () => {
if (result || result === 0) {
isFloat = false;
signOn = false;
firstNumber = String(result);
operator = operatorButton.dataset.operator;
result = "";
screen.value = `${firstNumber} ${operatorButton.textContent} `;
} else if (operator && ![" ", "+", "-", "."].includes(screen.value[screen.value.length - 1])) {
calculate();
isFloat = false;
signOn = false;
firstNumber = String(result);
operator = operatorButton.dataset.operator;
result = "";
screen.value = `${firstNumber} ${operatorButton.textContent} `;
} else if (!operator) {
isFloat = false;
firstNumber = screen.value;
operator = operatorButton.dataset.operator;
screen.value += ` ${operatorButton.textContent} `;
} else if (!signOn
&& !["*", "/"].includes(operatorButton.dataset.operator)
&& screen.value[screen.value.length - 1] === " ") {
signOn = true;
screen.value += operatorButton.textContent;
}
});
});
equalsButton.addEventListener("click", calculate);
* {
box-sizing: border-box;
font-family: 'Roboto', sans-serif;
font-weight: 300;
margin: 0;
padding: 0;
}
body {
background-color: #222;
height: 100vh;
}
header {
background-color: #333;
padding: 40px 0;
}
header h1 {
-webkit-background-clip: text;
background-clip: text;
background-image: linear-gradient(to right bottom, #fff, #777);
color: transparent;
font-size: 40px;
letter-spacing: 2px;
text-align: center;
text-transform: uppercase;
}
main {
background-color: #222;
display: flex;
justify-content: center;
padding: 60px 0;
}
main #container {
background-color: #333;
box-shadow: 0 5px 5px #111;
padding: 20px;
}
.clearfix:after {
clear: both;
content: " ";
display: block;
font-size: 0;
height: 0;
visibility: hidden;
}
#container .row:not(:last-child) {
margin-bottom: 9px;
}
#container input,
#container button {
float: left;
}
#container input:focus,
#container button:focus {
outline: none;
}
#container input {
background-color: #222;
border: 1px solid #999;
border-right-width: 0;
color: #999;
font-size: 22px;
font-weight: 300;
height: 80px;
padding-right: 14px;
text-align: right;
width: 261px;
}
#container button {
background-color: #222;
border: none;
box-shadow: 0 3px 0 #111;
color: #999;
font-size: 20px;
height: 80px;
margin-right: 7px;
width: 80px;
}
#container button:active {
box-shadow: 0 2px 0 #111;
transform: translateY(1px);
}
#container #clear,
#container .operator,
#container #equals {
color: #111;
}
#container #clear,
#container .operator {
margin-right: 0;
}
#container #clear {
background-color: #e95a4b;
border: 1px solid #999;
border-left-width: 0;
box-shadow: none;
cursor: pointer;
}
#container #clear:active {
box-shadow: none;
transform: none;
}
#container .operator {
background-color: #999;
box-shadow: 0 3px 0 #555;
}
#container .operator:active {
box-shadow: 0 2px 0 #555;
}
#container #equals {
background-color: #2ecc71;
box-shadow: 0 3px 0 #155d34;
}
#container #equals:active {
box-shadow: 0 2px 0 #155d34;
}
#media only screen and (max-width: 400px) {
header {
padding: 28px 0;
}
header h1 {
font-size: 36px;
}
main {
padding: 40px 0;
}
main #container {
padding: 16px;
}
#container .row:not(:last-child) {
margin-bottom: 7px;
}
#container input {
font-size: 18px;
height: 60px;
padding-right: 10px;
width: 195px;
}
#container button {
font-size: 16px;
height: 60px;
margin-right: 5px;
width: 60px;
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Calculator</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://fonts.googleapis.com/css?family=Roboto:300" rel="stylesheet">
<link href="Project 1.css" rel="stylesheet">
</head>
<body>
<header>
<h1>Calculator</h1>
</header>
<main>
<div id="container">
<div class="row clearfix">
<input id="screen" value="0" disabled type="text">
<button id="clear">AC</button>
</div>
<div class="row clearfix">
<button class="number">1</button>
<button class="number">2</button>
<button class="number">3</button>
<button data-operator="+" class="operator">+</button>
</div>
<div class="row clearfix">
<button class="number">4</button>
<button class="number">5</button>
<button class="number">6</button>
<button data-operator="-" class="operator">-</button>
</div>
<div class="row clearfix">
<button class="number">7</button>
<button class="number">8</button>
<button class="number">9</button>
<button data-operator="*" class="operator">×</button>
</div>
<div class="row clearfix">
<button id="decimal">.</button>
<button class="number">0</button>
<button id="equals">=</button>
<button data-operator="/" class="operator">÷</button>
</div>
</div>
</main>
<script src="Project 1.js"></script>
</body>
</html>
This is the code for the calc.. Feel free to edit it and explain to me what you did.
There is already one.
The Math.sqrt() function returns the square root of a number, that is, ∀x≥0,Math.sqrt(x)=x
=the uniquey≥0such thaty2=x
MDN Docs
You can use javascript built in
Math.sqrt(number)

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