Concat function not working or bad if then statement? - javascript

I'm making a calculator and ran into some issues with an if/else function giving me unexpected results. The logic seems kind of sound when I run it over so I would like some input on what I may have wrong here. The code is giving unexpected results from expressionMaker where it seems to clear the first "if --> if " statements but none of the else ones.
Edit: thanks for the feedback. I've narrowed the issue down to this portion.
else if ((EventTarget == numbers) && (expression.a > 0) && (expression.operand !== 0)) {
if (expression.b == 0) {
expression.b = keyValue
}
else {
expression.b = concat(expression.b, keyValue)
}
}
const btn = document.getElementById("calculatorGrid");
const display = document.getElementById("display");
const miniscreen = document.getElementById("miniScreen")
const equals = document.getElementById("evaluate")
const numbers = document.querySelectorAll(".Nbuttons");
const clear = document.getElementById("clear");
const add = document.getElementById("plus");
const sub = document.getElementById("subtract");
const multi = document.getElementById("multiply");
const divi = document.getElementById("divide");
const operators = document.querySelectorAll(".operators");
let nums = document.getElementById("nums")
numbers.values = nums.textContent
const calculate = (() => {
const add = (a, b) => a + b;
const sub = (a, b) => a - b;
const mul = (a, b) => a * b;
const div = (a, b) => a / b;
return {
add,
sub,
mul,
div,
};
});
const expression = {
a: 0,
operand: 0,
b: 0,
};
function expressionMaker(keyValue) {
const concat = (a, b) => {
return ("" + a + b)
};
if (EventTarget == numbers && expression.a == 0 || expression.operand == 0) {
if (expression.a == 0) {
expression.a = keyValue
}
else if (expression.a > 0) {
expression.a = concat(expression.a, keyValue)
}
display.innerHTML = expression.a
}
else if ((EventTarget == numbers) && (expression.a > 0) && (expression.operand !== 0)) {
if (expression.b == 0) {
expression.b = keyValue
}
else {
expression.b = concat(expression.b, keyValue)
}
}
else {
null
}
}
function evaluate() {
var result
if (expression.operand == "+") {
var result = calculate.add(expression.a, expression.b)
}
else if (expression.operand == "-") {
result = calculate.sub(expression.a, expression.b)
}
else if (expression.operand == "x") {
result = calculate.mul(expression.a, expression.b)
}
else if (expression.operand == "/") {
result = calculate.div(expression.a, expression.b)
}
else {
return null
}
display.innerHTML = result
return result
}
clear.addEventListener("click", () => {
clearOut()
})
equals.addEventListener("click", () => {
evaluate(expression.a, expression.b)
})
function setNums() {
let nums = document.getElementById("nums")
numbers.values = nums.textContent
};
setNums();
function clearOut() {
display.textContent = 0
expression.a = 0
expression.operand = 0
expression.b = 0
};
clear.addEventListener("click", function() {
clearOut();
});
add.addEventListener("click", () => {
expression.operand = "+"
display.innerHTML = "+"
})
sub.addEventListener("click", () => {
expression.operand = "-"
display.innerHTML = "-"
})
multi.addEventListener("click", () => {
expression.operand = "x"
display.innerHTML = "x"
})
divi.addEventListener("click", () => {
expression.operand = "/"
display.innerHTML = "/"
})
numbers.forEach(function(element) {
element.addEventListener("click", function(event) {
var key = event.target
let keyValue = key.textContent
expressionMaker(keyValue)
});
});
<!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">
<title>Calculator</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div id="display">
<div id="miniScreen"></div>
</div>
<div id="calculatorGrid">
<button class="Nbuttons" id="nums" data-number="1">1</button>
<button class="Nbuttons" id="nums" data-number="2">2</button>
<button class="Nbuttons" id="nums" data-number="3">3</button>
<button class="Nbuttons" id="nums" data-number="4">4</button>
<button class="Nbuttons" id="nums" data-number="5">5</button>
<button class="Nbuttons" id="nums" data-number="6">6</button>
<button class="Nbuttons" id="nums" data-number="7">7</button>
<button class="Nbuttons" id="nums" data-number="8">8</button>
<button class="Nbuttons" id="nums" data-number="9">9</button>
<button class="Nbuttons" id="nums" data-number="0">0</button>
<button class="operators" id="plus" data-operator="+">+</button>
<button class="operators" id="subtract" data-operator="-">-</button>
<button class="operators" id="multiply" data-operator="*">x</button>
<button class="operators" id="divide" data-operator="/">÷</button>
<button id="clear">clear</button>
<button id="evaluate"> =</button>
</div>
<script src="script.js" defer></script>
</body>
</html>

Let's start with the beginning, you can replace this function, with 4 separate "addEventListener", it's going to be way less confusing and less error prone.
operators.forEach(function(element) {
element.addEventListener("click", function() {
if (EventTarget == add) {
expression.operand = "+"
display.innerHTML = "+"
}
else if (EventTarget == sub) {
expression.operand = "-"
display.innerHTML = "-"
}
else if (EventTarget == multi) {
expression.operand = "x"
display.innerHTML = "x"
}
else if (EventTarget == divi) {
expression.operand = "/"
display.innerHTML = "/"
}
})
})
New version:
add.addEventListener("click", function() {
expression.operand = "+";
display.innerHTML += "+";
});
sub.addEventListener("click", function() {
expression.operand = "-";
display.innerHTML += "-";
});
multi.addEventListener("click", function() {
expression.operand = "x";
display.innerHTML += "x";
});
divi.addEventListener("click", function() {
expression.operand = "/";
display.innerHTML += "/";
});
The thing with the "unexpected behavior" is that I'm not sure what your logic was trying to do, the only thing I can suggest you is take a look at this: https://developer.chrome.com/docs/devtools/javascript/ you'll debug a lot while coding, so it's always great to give it a try.
Using the developer tools, you'll be able to see the values in every variable at each step, that should make it easier for you to find where things are going south.

I hope the below answer is suitable for you.
may be your elements have duplicate id like id="nums"
you can also complete like this..
const miniscreen = document.getElementById("miniScreen");
function clearValue(){
miniscreen.innerHTML=0;
}
function mini(param){
if(miniscreen.innerHTML==0){
miniscreen.innerHTML=param;
}else{
miniscreen.innerHTML+=param;
}
}
function calculate(){
miniscreen.innerHTML=eval(miniscreen.innerHTML);
}
<body>
<div id="display">
<div id="miniScreen">0</div>
</div>
<div id="calculatorGrid">
<button class="Nbuttons" onclick="mini('1')" data-number="1">1</button>
<button class="Nbuttons" onclick="mini('2')" data-number="2">2</button>
<button class="Nbuttons" onclick="mini('3')" data-number="3">3</button>
<button class="Nbuttons" onclick="mini('4')">4</button>
<button class="Nbuttons" onclick="mini('5')">5</button>
<button class="Nbuttons" onclick="mini('6')">6</button>
<button class="Nbuttons" onclick="mini('7')">7</button>
<button class="Nbuttons" onclick="mini('8')">8</button>
<button class="Nbuttons" onclick="mini('9')">9</button>
<button class="Nbuttons" onclick="mini('0')">0</button>
<button class="operators" id="plus" onclick="mini('+')">+</button>
<button class="operators" id="subtract" onclick="mini('-')">-</button>
<button class="operators" id="multiply" onclick="mini('*')">x</button>
<button class="operators" id="divide" onclick="mini('/')">÷</button>
<button id="clear" onclick="clearValue()">clear</button>
<button id="evaluate" onclick="calculate()"> =</button>
</div>
</body>
Thank you.

Related

JS Calculator - what is wrong with my code?

EDIT 2: I'm just starting again from scratch. No point in trying to understand these complex problems problems right now when I am a novice. Have consulted someone from my cohort who can go through it with me. I appreciate the advice and insight.
I have been editing this code heavily, as the original relied a constructor. The calculator does not currently append any numbers to either displays when pushed, and I am not sure why! I think the problem lies somewhere in the appending/ node process or the update display function! Any and all advice/ ideas welcomed.
For context I am 5 weeks into a 12 week intensive course and am a baby baby baby coder. Please explain like I am 5!!!
EDIT: If you want to see original code please look at my previous question!
JAVA SCRIPT
const calculator =
(previousOperandTextElement, currentOperandTextElement, operation);
clear = () => {
currentOperand = "";
previousOperand = "";
operation = undefined;
};
remove = () => {
currentOperand = currentOperand.toString().slice(0, -1);
};
chooseOperation = (operation) => {
if (currentOperand === "") return;
if (previousOperand !== "") {
compute();
}
operation = operation;
previousOperand = currentOperand;
currentOperand = "";
};
compute = () => {
let computation;
const prev = parseFloat(previousOperand);
const current = parseFloat(currentOperand);
if (isNaN(prev) || isNaN(current)) return;
switch (operation) {
case "+":
computation = prev + current;
break;
case "-":
computation = prev - current;
break;
case "*":
computation = prev * current;
break;
case "÷":
computation = prev / current;
break;
default:
return;
}
currentOperand = computation;
operation = undefined;
previousOperand = "";
};
getDisplayNumber = (number) => {
const stringNumber = number.toString();
const integerDigits = parseFloat(stringNumber.split(".")[0]);
const decimalDigits = stringNumber.split(".")[1];
let integerDisplay;
if (isNaN(integerDigits)) {
integerDisplay = "";
} else {
integerDisplay = integerDigits.toLocaleString("en", {
maximumFractionDigits: 0,
});
}
if (decimalDigits != null) {
return `${integerDisplay}.${decimalDigits}`;
} else {
return integerDisplay;
}
};
updateDisplay = () => {
currentOperandTextElement.innerText = getDisplayNumber(currentOperand);
if (operation != null) {
previousOperandTextElement.innerText = `${getDisplayNumber(
previousOperand
)} ${operation}`;
} else {
previousOperandTextElement.innerText = "";
}
};
appendNumber = (number) => {
if (number === "." && currentOperand.includes(".")) return;
currentOperand = currentOperand.toString() + number.toString();
};
equalsButton.addEventListener("click", (button) => {
calculator.compute();
calculator.updateDisplay();
});
numberButtons.forEach = (button) => {
button.addEventListener("click", () => {
calculator.appendNumber(button.innerText);
calculator.updateDisplay();
});
};
operationButtons.forEach = (button) => {
button.addEventListener("click", () => {
calculator.chooseOperation(button.innerText);
calculator.updateDisplay();
});
};
allClearButton.addEventListener("click", (button) => {
calculator.clear();
calculator.updateDisplay();
});
deleteButton.addEventListener("click", (button) => {
calculator.delete();
calculator.updateDisplay();
});
item = (previousOperandTextElement, currentOperandTextElement) => {
previousOperandTextElement = previousOperandTextElement;
currentOperandTextElement = currentOperandTextElement;
clear();
};
const numberButtons = document.querySelectorAll("[data-number]");
const operationButtons = document.querySelectorAll("[data-operation]");
const equalsButton = document.querySelector("[data-equals]");
const deleteButton = document.querySelector("[data-delete]");
const allClearButton = document.querySelector("[data-all-clear]");
const previousOperandTextElement = document.querySelector(
"[data-previous-operand]"
);
const currentOperandTextElement = document.querySelector(
"[data-current-operand]"
);
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>Calculator</title>
<script src="calcedit.js" defer></script>
</head>
<body>
<div class="calculator-grid">
<div class="output">
<div data-previous-operand class="previous-operand"></div>
<div data-current-operand class="current-operand"></div>
</div>
<button data-all-clear class="span-two">AC</button>
<button data-delete>DEL</button>
<button data-operation>÷</button>
<button data-number>1</button>
<button data-number>2</button>
<button data-number>3</button>
<button data-operation>x</button>
<button data-number>4</button>
<button data-number>5</button>
<button data-number>6</button>
<button data-operation>+</button>
<button data-number>7</button>
<button data-number>8</button>
<button data-number>9</button>
<button data-operation>-</button>
<button data-number>.</button>
<button data-number>0</button>
<button data-equals class="span-two">=</button>
</div>
</body>
</html>
So reading through your code, this issue is related to your understanding of your previous question
removing the Class means you no longer have a calculator instance or Object to work with so you can to work in a more procedural way
To start with
const calculator =
(previousOperandTextElement, currentOperandTextElement, operation);
Should be replaced with
var previousOperandTextElement = "",
currentOperandTextElement = "",
operation;
Anywhere you've got calculator for example calculator.compute(); should just be replaced with the new function you've created, in this case compute(); because you don't have a calculator object to work with.
As the previous comments suggested, for this may not be a good approach and a class / prototype approach might be better (what you had originally)

is there any method in javascript to operate a function singly for one HTML element?

I have three box in my web page , each box includes a + button , a - button and a span with pre-assigned value as 0.
I want when I click on + or - button, the value of span get one more or less according to times of clicking + or -.
but my code doesnt work well.
what should I do ?
Thanks.
<div class="box">
<button class="minus-btn" type="button">-</button>
<span class="display-num">0</span>
<button class="plus-btn" type="button">+</button>
</div>
<div class="box">
<button class="minus-btn" type="button">-</button>
<span class="display-num">0</span>
<button class="plus-btn" type="button">+</button>
</div>
<div class="box">
<button class="minus-btn" type="button">-</button>
<span class="display-num">0</span>
<button class="plus-btn" type="button">+</button>
</div>
function $(query) {
return document.querySelector(query);
}
function $All(query) {
return document.querySelectorAll(query);
}
const box = $All('.box');
const plusBtn = $All('.plus-btn');
const minusBtn = $All('.minus-btn');
const displayNum = $All('.display-num');
box.forEach((e) => {
e.addEventListener('click', (el) => {
if (el.target.classList.contains('plus-btn')) {
let num = 0;
displayNum.forEach((e) => {
e.innerHTML = num++;
})
} else if (el.target.classList.contains('minus-btn')) {
let num = 0;
displayNum.forEach((e) => {
e.innerHTML = num--;
})
}
}, false)
})
It is probably easier to react on the actual button being pressed, rather than checking the boxes etc, try the following:
plusBtn.forEach((e, idx) => {
e.addEventListener(
'click',
(el) => {
calcIt(displayNum[idx], 1);
},
false
);
});
minusBtn.forEach((e, idx) => {
e.addEventListener(
'click',
(el) => {
calcIt(displayNum[idx], -1);
},
false
);
});
function calcIt(element, value) {
var num = element.innerHTML;
element.innerHTML = (+num) + value;
}
Remove the block:
box.forEach((e) => {
e.addEventListener('click', (el) => {
if (el.target.classList.contains('plus-btn')) {
let num = 0;
displayNum.forEach((e) => {
e.innerHTML = num++;
})
} else if (el.target.classList.contains('minus-btn')) {
let num = 0;
displayNum.forEach((e) => {
e.innerHTML = num--;
})
}
}, false)
})
Stackblitz:
https://jquery-rfrzsp.stackblitz.io
(https://stackblitz.com/edit/jquery-rfrzsp)

comment appending on the first post only in Vanilla JavaScript

I am creating a status posting and commenting system.
It is implemented in Vanilla JavaScript. Anyone can add a post and can comment on the post.
Everything is working fine but the comment section is working on first post only.
deletion of comment and post is working fine.
I don't know what's the problem is, if anyone could help me..
Here is the HTML code
<div class="container-post" id="container-post">
<div class="create-post">
<form>
<div class="form-group">
<div class="username">
<p class="name" style="top:15px;">User Name</p>
</div>
<p class="qoutes">
<textarea style=" font-size: 15pt;" class="form-control" id="enter-post" rows="7" id="mypara" placeholder="Share Your Thoughts..."></textarea>
</p>
<div class="postbar">
<button type="button" class="btn btn-primary post-me" id="post-button"> <span id="postText">Post</span></button>
</div>
</div>
</form>
</div>
<hr class="line-bar">
<div class="allpost">
<div class="mainpost" id="post-div"></div>
</div>
Here is the JavaSCript code
showTask();
showComment();
let addPost = document.getElementById("enter-post");
let addPostBtton = document.getElementById("post-button");
addPostBtton.addEventListener("click", function () {
var addPostVal = addPost.value;
if (addPostVal.trim() != 0) {
let webtask = localStorage.getItem("localtask");
if (webtask == null) {
var taskObj = [];
}
else {
taskObj = JSON.parse(webtask);
}
taskObj.push(addPostVal);
localStorage.setItem("localtask", JSON.stringify(taskObj));
}
showTask();
});
function showTask() {
let webtask = localStorage.getItem("localtask");
if (webtask == null) {
var taskObj = [];
}
else {
taskObj = JSON.parse(webtask);
}
let htmlVal = '';
let createPost = document.getElementById("post-div");
taskObj.forEach((item, index) => {
htmlVal += `
<div class="post-class"><div class="username u-name">
<p class="name i-name">${"User Name " + index}</p>
<i class="fas fa-trash-alt" onclick="removePost(${index});"></i></button>
</div>
<hr>
<p class="quotes">
${item}
</p>
<div class="comment-section" id="comment-section">
<p class="comment-qoute">
<textarea style=" font-size: 15pt;" class="form-control commentBox" rows="3" id="mypara" placeholder="Leave a comment"></textarea>
</p>
<button class="btn btn-primary comment-btn" id="commentBtn">comment</button>
<ul class="comments" id="comments-portion">
<p></p>
</ul>
</div>
</div>
<br><br>`
});
createPost.innerHTML = htmlVal;
}
function removePost(index) {
let webtask = localStorage.getItem("localtask");
let taskObj = JSON.parse(webtask);
taskObj.splice(index, 1);
localStorage.setItem("localtask", JSON.stringify(taskObj));
showTask();
}
var commentPost = document.getElementById('mypara');
var commentBtn = document.getElementById('commentBtn');
commentBtn.addEventListener('click', function () {
var commentValue = commentPost.value;
if (commentValue.trim() != 0) {
let commentTask = localStorage.getItem("comments");
if (commentTask == null) {
var commentObj = [];
}
else {
commentObj = JSON.parse(commentTask);
}
commentObj.push(commentValue);
localStorage.setItem("comments", JSON.stringify(commentObj));
}
showComment();
});
function showComment() {
let commentsTask = localStorage.getItem("comments");
if (commentsTask == null) {
var commentObj = [];
}
else {
commentObj = JSON.parse(commentsTask);
}
let commentHTMLValue = '';
var createComment = document.getElementById("comments-portion");
commentObj.forEach((item, index) => {
commentHTMLValue += `<div class="comment-box-btn">
<p>${index + ". "}<span>${item}</span></p>
<i class="far fa-times-circle fa-2x" onclick="removeComment(${index});"></i>
</div>
`;
});
createComment.innerHTML = commentHTMLValue;
}
var deleteBtn = document.querySelector('.comment-del');
deleteBtn.addEventListener('click', () => {
});
// remove comment
function removeComment(index) {
let commentTask = localStorage.getItem("comments");
let commentObj = JSON.parse(commentTask);
commentObj.splice(index, 1);
localStorage.setItem("comments", JSON.stringify(commentObj));
showComment();
}
When you use code like:
createComment.innerHTML = commentHTMLValue;
you are completely replacing the contents of the element. Try using:
createComment.innerHTML += commentHTMLValue;
which appends new content to the end of the existing contents.
I can't do a snippet here as the use of localStorage is not allowed. Copy this block into a blank file and save it as an html file and then open that in a browser.
This is how I think you are describing your requirements and is also based on the data format in my comments. It's not pretty and needs plenty of sprucing up, but it runs.
<!DOCTYPE html>
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8">
<html>
<head>
<title>Task listing</title>
<script type="text/javascript">
let taskList = [];
function checkTasks() {
let tasksList = getTasksList();
if (tasksList.length == 0) {
let newTask = prompt("Please enter a task description");
if (newTask) {
let thisIndex = getNewIndex();
let a = {"id": thisIndex, "task": newTask, "comments": []}
taskList.push(a);
saveTasksList(taskList);
}
}
displayTasks();
}
function displayTasks() {
let container = document.getElementById("tasks");
container.innerHTML = "";
let taskList = getTasksList();
taskList.forEach(function(task){
let d = document.createElement("div");
d.id = "task_" + task.id;
d.className = "commentdiv";
d.innerHTML = "<h3>" + task.task + "</h3>";
let l = document.createElement("ul");
l.id = "comments_" + task.id;
let comments = task.comments;
if (comments.length > 0) {
let commentindex = 0;
comments.forEach(function(comment) {
let c = document.createElement("li");
c.innerHTML = comment;
let cb = document.createElement("button");
cb.id = "deletecomment_" + task.id + "_" + commentindex;
cb.innerHTML = "Delete comment";
cb.onclick = function() {deleteComment(task.id, commentindex);};
c.appendChild(cb);
l.appendChild(c);
})
}
let b = document.createElement("button");
b.id = "addcomment_" + task.id;
b.onclick = function() {addComment(task.id);};
b.innerHTML = "Add comment";
d.appendChild(b);
d.appendChild(l);
container.appendChild(d);
})
}
function addComment(taskid) {
let newcomment = prompt("Enter comment");
if (newcomment) {
let tasklist = getTasksList();
let filtered = tasklist.filter(task => task.id == taskid);
if (filtered[0]) {
let thisTask = filtered[0];
thisTask.comments.push(newcomment);
let thisIndex = taskList.findIndex((task) => task.id == taskid);
taskList[thisIndex] = thisTask;
}
saveTasksList(taskList);
displayTasks();
}
}
function addNewTask() {
let newTask = prompt("Enter task description");
let taskList = getTasksList();
let lastindex = localStorage.getItem("tasksindex");
let index = getNewIndex();
let a = {"id": index, "task": newTask, "comments": []}
taskList.push(a);
saveTasksList(taskList);
displayTasks();
}
function deleteComment(taskid, commentindex) {
let tasklist = getTasksList();
let filtered = tasklist.filter(task => task.id == taskid);
// as long as there is at least one task with the taskid value, find and delete the comment
// based on the index position of the comment in the comments array
if (filtered[0]) {
let thisTask = filtered[0];
thisTask.comments.splice(commentindex, 1);
let thisIndex = taskList.findIndex((task) => task.id == taskid);
taskList[thisIndex] = thisTask;
}
saveTasksList(taskList);
displayTasks();
}
function getTasksList() {
let tasks = localStorage.getItem("tasks");
taskList = JSON.parse(tasks);
if (!taskList) {
taskList = [];
}
return taskList;
}
function saveTasksList(taskList) {
localStorage.setItem("tasks", JSON.stringify(taskList));
}
function getNewIndex() {
let lastindex = localStorage.getItem("tasksindex");
let idx = 0;
if (!lastindex) {
idx = 1;
} else {
idx = Number(lastindex) + 1;
}
localStorage.setItem("tasksindex", idx);
return idx;
}
function removeAll() {
localStorage.removeItem("tasks");
localStorage.removeItem("tasksindex");
displayTasks();
}
window.onload = checkTasks;
</script>
<style type="text/css">
.commentdiv {
border:1px solid black;
width:1000px;
padding:5px;
border-radius:5px;
}
button {
margin-left:10px;
}
h3 {
width:100%;
border-bottom: 1px dotted black;
}
ul {
list-style-type:decimal;
}
</style>
</head>
<body>
<h2>My task list <button id="addNewTaskButton" onclick="addNewTask();">Add new task</button></h2>
<hr>
<div id="tasks">
</div>
<button id="removeAll" onclick="removeAll();">Remove all tasks</button>
</body>
</html>

Images not showing up in Javascript

This is supposed to be a dice game where 2 people click to roll dice and they add what they get until they reach the goal. Their score resets if they roll over 9 though. Images of dice are supposed to pop up and show what they rolled. I know the images are not on here but it still shows that there should an image there with the error symbol. I am having trouble with the second image not showing up which should come from the SetPic2 function. Any help would be appreciated. Also, the PASS buttons are supposed the pass the person's turn to the other player but the main problem is the images.
//console.log("file loaded");
//var p1Button = document.getElementById("p1");
var p1Button = document.querySelector("#p1");
var p2Button = document.querySelector("#p2");
var P1Pass = document.querySelector("P1Pass");
var P2Pass = document.querySelector("P2Pass");
var setButton = document.querySelector("#set");
var resetButton = document.querySelector("#reset");
var diceImage = document.querySelector("img");
var diceImage2 = document.querySelector("img2");
var p1Total = document.querySelector("#p1score");
var p2Total = document.querySelector("#p2score");
var targetScore = document.querySelector("#tscore");
var newScore = document.querySelector("#newtarget");
var num = 0,
num2 = 0,
p1val = 0,
p2val = 0,
target;
var playgame = true;
target = Number(targetScore.textContent); //convert the string to num
p1Button.addEventListener("click", function() {
if (playgame) {
//Math.random() --> return a value between 0 & 1
num = Math.floor((Math.random() * 6) + 1);
num2 = Math.floor((Math.random() * 6) + 1);
p1val = p1val + num + num2;
p1Total.textContent = p1val;
setButton.disabled = true;
p1Button.disabled = true;
p2Button.disabled = false;
setPic(num);
setPic2(num2);
if (num + num2 > 9) {
p1val = 0;
}
if (p1val >= target) {
playgame = false;
p1Total.classList.add("winner");
stopGame();
}
}
});
p2Button.addEventListener("click", function() {
if (playgame) {
//Math.random() --> return a value between 0 & 1
num = Math.floor((Math.random() * 6) + 1);
num2 = Math.floor((Math.random() * 6) + 1);
p2val = p2val + num + num2;
p2Total.textContent = p2val;
setButton.disabled = true;
p1Button.disabled = false;
p2Button.disabled = true;
setPic(num);
setPic2(num2);
if (num + num2 > 9) {
p2val = 0;
}
if (p2val >= target) {
playgame = false;
p2Total.classList.add("winner");
stopGame();
}
}
});
/*P1Pass.addEventListener("click", function(){
p1Button.disabled= true;
p2Button.disabled = false;
});
P2Pass.addEventListener("click", function(){
p1Button.disabled = false;
p2Button.disabled = true;
});*/
setButton.addEventListener("click", function() {
targetScore.textContent = newScore.value;
target = Number(targetScore.textContent);
setButton.disabled = true;
newScore.disabled = true;
});
resetButton.addEventListener("click", function() {
p1Button.disabled = false;
p2Button.disabled = true;
p1Total.textContent = "0";
p2Total.textContent = "0";
targetScore.textContent = "25";
setButton.disabled = false;
newScore.disabled = false;
p1Total.classList.remove("winner");
p2Total.classList.remove("winner");
playgame = true;
p1val = 0;
p2val = 0;
target = 25;
});
function stopGame() {
p1Button.disabled = true;
p2Button.disabled = true;
setButton.disabled = true;
newScore.disabled = true;
}
function setPic(val) {
if (val == 1) {
diceImage.src = "1.png";
} else if (val == 2) {
diceImage.src = "2.png";
} else if (val == 3) {
diceImage.src = "3.png";
} else if (val == 4) {
diceImage.src = "4.png";
} else if (val == 5) {
diceImage.src = "5.png";
} else if (val == 6) {
diceImage.src = "6.png";
}
}
function setPic2(val2) {
if (val2 == 1) {
diceImage2.src = "1.png";
} else if (val2 == 2) {
diceImage2.src = "2.png";
} else if (val2 == 3) {
diceImage2.src = "3.png";
} else if (val2 == 4) {
diceImage2.src = "4.png";
} else if (val2 == 5) {
diceImage2.src = "5.png";
} else if (val2 == 6) {
diceImage2.src = "6.png";
}
}
.winner {
color: green;
background-color: yellow;
}
;
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initialscale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap
.min.css" integrity="sha384-
Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<link rel="stylesheet" href="gamestyle.css">
<title>Dice Game</title>
</head>
<body>
<div class="container">
<br>
<h1> <span id="p1score">0</span> vs. <span id="p2score">0</span> </h1>
<br>
<p>Target-Score: <span id="tscore">25</span></p>
<br>
<button class="btn btn-success" id="p1"> Player One </button>
<button class="btn btn-warning" id="p2"> Player Two </button>
<br><br>
<button class="btn btn-secondary" id="P1Pass">PASS</button>
<button class="btn btn-secondary" id="P2Pass">PASS</button>
<br><br> New Target: <input type="number" id="newtarget">
<br><br>
<button class="btn btn-primary" id="set"> Set </button>
<button class="btn btn-danger" id="reset"> Reset </button>
<br><br>
<img src="">
<img src="">
</div>
<script src="gamefunction.js"></script>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-
J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min
.js" integrity="sha384-
Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.m
in.js" integrity="sha384-
wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
</body>
</html>
Your selector will not finding your second image element.
var diceImage2 = document.querySelector("img2");
You could give your images IDs and reference them directly:
HTML
<img id="die1" src="" />
<img id="die2" src="" />
JS
var diceImage1 = document.getElementById('die1');
var diceImage2 = document.getElementById('die2');

Add or Clear localStorage on button click and show the value in html

I have a code that uses localStorage and javascript. I tried to add more slots, like slot1, slot2, slot3 up to 5. I just copy and paste then change the variable names like like slot1, slot2, slot3 up to 5. But it won't work. Help will be appreciated so much.
Javascript:
var slot = localStorage.getItem("slot");
if (slot == null) {
slot = 10;
}
document.getElementById("slot").innerText = slot;
function reduceSlot() {
if (slot >= 1) {
slot--;
localStorage.setItem("slot", slot);
if (slot > 0) {
document.getElementById('slot').innerText = slot;
} else {
document.getElementById('slot').innerText = "FULL";
document.getElementById("button1").style.display = "none";
}
}
}
document.getElementById("button1").onclick = reduceSlot;
function clearLocalStorage() {
localStorage.clear();
}
HTML:
<p id="slot">10</p>
Deduct
<button onclick="window.localStorage.clear();">Clear All</button>
Fiddle: http://jsfiddle.net/barmar/K8stQ/3/
not sure but. is this what you want to do?? working demo
i changed your code a bit.. you can change it into your liking later..
<span id="slot0">10</span><input type="button" value="Deduct" onclick="(function(){reduceSlot(0)})()" ><br>
<span id="slot1">10</span><input type="button" value="Deduct" onclick="(function(){reduceSlot(1)})()" ><br>
<span id="slot2">10</span><input type="button" value="Deduct" onclick="(function(){reduceSlot(2)})()" ><br>
<span id="slot3">10</span><input type="button" value="Deduct" onclick="(function(){reduceSlot(3)})()" ><br>
<span id="slot4">10</span><input type="button" value="Deduct" onclick="(function(){reduceSlot(4)})()" ><br>
<p>
<button onclick="clearAll()">Clear All</button>
</p>
and for the js...
ls = localStorage.getItem("slots") ;
if(!ls) { localStorage.setItem("slots", "10,10,10,10,10");
}
var slots = localStorage.getItem("slots").split(',').map(Number);
window.onload = updateSlots;
function updateSlots() { for(var i=0;i<slots.length;i++) {
document.getElementById('slot' + i ).innerHTML = slots[i] ;
}}
var reduceSlot = function(slotId) {
console.log(slots[slotId]) ;
if(slots[slotId] >= 1) {
slots[slotId]--; localStorage.setItem("slots",slots);
document.getElementById('slot' + slotId).innerHTML = slots[slotId];
}
else { document.getElementById('slot'+slotId).innerText = "FULL";
}
};
function clearAll() {
window.localStorage.clear();
slots = [10,10,10,10,10];
updateSlots();
}
Try this,
Script
window.ready = function() {
checkStorage();
}
function checkStorage() {
var slot = localStorage.getItem("slot");
if (slot == null) {
slot = 10;
}
document.getElementById("slot").innerHTML = slot;
}
function reduceSlot() {
var slot = localStorage.getItem("slot");
if (slot == null) {
slot = 10;
}
if (slot >= 1) {
slot--;
localStorage.setItem("slot", slot);
if (slot > 0) {
document.getElementById('slot').innerHTML = slot;
} else {
document.getElementById('slot').innerHTML = "FULL";
document.getElementById("button1").style.display = "none";
}
}
}
document.getElementById("button1").onclick = reduceSlot;
document.getElementById("clear").onclick = clear_me;
function clear_me() {
localStorage.clear();
checkStorage();
}
HTML
<p id="slot">10</p>
Deduct
<button id="clear">Clear All</button>
Demo

Categories