Calculator doesn't display result [closed] - javascript

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 months ago.
Improve this question
*This calculator is only for one digit calculations
In my code there are 3 textboxes Two for values and one for Operators.
I want that if first textbox isn't empty and user clicks on any number than that value should be added in another textbox.
When I click Enter it doesn't display result and I didn't show any kind of error in console
// Textboxes, Enter and Reset
var txt1 = document.querySelector("#txt1");
var txt2 = document.querySelector("#txt2");
var txt3 = document.querySelector("#txt3");
var ent = document.querySelector("#ent");
var res = document.querySelector("#res");
// Number-Buttons
var b1 = document.querySelector("#b1");
var b2 = document.querySelector("#b2");
var b3 = document.querySelector("#b3");
var b4 = document.querySelector("#b4");
var b5 = document.querySelector("#b");
var b6 = document.querySelector("#b6");
var b7 = document.querySelector("#b7");
var b8 = document.querySelector("#b8");
var b9 = document.querySelector("#b9");
// Operators
var add = document.querySelector("#add");
var sub = document.querySelector("#sub");
var mul = document.querySelector("#mul");
var div = document.querySelector("#div");
if (txt1.value == "") {
function B1() { txt1.value = "1" }
function B2() { txt1.value = "2" }
function B3() { txt1.value = "3" }
function B4() { txt1.value = "4" }
function B5() { txt1.value = "5" }
function B6() { txt1.value = "6" }
function B7() { txt1.value = "7" }
function B8() { txt1.value = "8" }
function B9() { txt1.value = "9" }
if (txt2.value == "") {
function Add() { txt2.value = "+" }
function Sub() { txt2.value = "-" }
function Mul() { txt2.value = "*" }
function Div() { txt2.value = "/" }
}
// if (txt1.value != "" && txt3.value == "") {
// function B1() { txt3.value = "1" }
// function B2() { txt3.value = "2" }
// function B3() { txt3.value = "3" }
// function B4() { txt3.value = "4" }
// function B5() { txt3.value = "5" }
// function B6() { txt3.value = "6" }
// function B7() { txt3.value = "7" }
// function B8() { txt3.value = "8" }
// function B9() { txt3.value = "9" }
// }
}
function Ent() {
if (txt1.value == "" || txt2.value == "" || txt3.value == "") {
alert("Pls Enter values and select the operator");
}
function sum() {
if (txt2.value == "+") {
var Sum = Number(txt1.value) + Number(txt3.value);
alert(Sum);
console.log(Sum);
}
}
function sub() {
if (txt2.value == "-") {
var Sub = Number(txt1.value) - Number(txt3.value);
alert(Sub);
console.log(Sub);
}
}
function mul() {
if (txt2.value == "*") {
var Mul = Number(txt1.value) * Number(txt3.value);
alert(Mul);
console.log(Mul);
}
}
function div() {
if (txt2.value == "/") {
var Div = Number(txt1.value) / Number(txt3.value);
alert(Div);
console.log(Div);
}
}
}

I tried to understand what you want to do from the code you shared. In the solution you developed, I made subtractions as the numbers are defined as separate buttons. In this direction, I developed a lean solution. This program is used as follows:
Use the numeric keypad to enter the first number.
Click the action you want to perform (+, -, *, /)
Use the numeric keypad to enter the second number.
Click the CALCULATE button to see the result.
Click the CLEAR button to clear the screen.
var firstNumberText = document.getElementById("txt1");
var secondNumberText = document.getElementById("txt2");
var operatorText = document.getElementById("txt3");
var operationText = document.getElementById("txt4");
var resultText = document.getElementById("txt5");
var addButton = document.getElementById("add");
var subButton = document.getElementById("sub");
var mulButton = document.getElementById("mul");
var divButton = document.getElementById("div");
var enterButton = document.getElementById("enter");
var clearButton = document.getElementById("clear");
let status = true;
let currentFirstNumber = "";
let currentSecondNumber = "";
function updateText(){
firstNumberText.innerText = currentFirstNumber;
secondNumberText.innerText = currentSecondNumber;
}
function changeState(operator) {
operatorText.innerText = operator;
status = !status;
}
addButton.addEventListener("click", function() {
changeState("+");
});
subButton.addEventListener("click", function() {
changeState("-");
});
mulButton.addEventListener("click", function() {
changeState("*");
});
divButton.addEventListener("click", function() {
changeState("/");
});
function numberPressed(pressedButton) {
if(status)
currentFirstNumber += pressedButton.value;
else
currentSecondNumber += pressedButton.value;
}
function updateResult(result, operator) {
operationText.innerText = firstNumberText.textContent + operator + secondNumberText.textContent + "=" + `${result}`;
resultText.innerText = result;
}
function calculate() {
if (firstNumberText.value == "" || secondNumberText.value == "" || operatorText.value == "") {
alert("Warning");
return;
}
var result = 0;
if(operatorText.textContent == "+") {
result = parseInt(firstNumberText.textContent) + parseInt(secondNumberText.textContent);
updateResult(result, "+");
}
else if(operatorText.textContent == "-") {
result = parseInt(firstNumberText.textContent) - parseInt(secondNumberText.textContent);
updateResult(result, "-");
}
else if(operatorText.textContent == "*") {
result = parseInt(firstNumberText.textContent) * parseInt(secondNumberText.textContent);
updateResult(result, "*");
}
else if(operatorText.textContent == "/") {
result = parseInt(firstNumberText.textContent) / parseInt(secondNumberText.textContent);
updateResult(result, "/");
}
}
enterButton.addEventListener("click", function() {
calculate();
});
clearButton.addEventListener("click", function() {
status = true;
currentFirstNumber = "";
currentSecondNumber = "";
firstNumberText.innerText = "";
secondNumberText.innerText = "";
operatorText.innerText = "";
operationText.innerText = "";
resultText.innerText = "";
});
<!-- First Number -->
<label id="txt1">-</label><br>
<!-- Operator -->
<label id="txt3">-</label><br>
<!-- Second Number -->
<label id="txt2">-</label><br>
<!-- Operation -->
<label id="txt4">-</label><br>
<!-- Result -->
<label id="txt5">-</label><br>
<button type="button" value="0" onclick='numberPressed(this);updateText()'>0</button>
<button type="button" value="1" onclick='numberPressed(this);updateText()'>1</button>
<button type="button" value="2" onclick='numberPressed(this);updateText()'>2</button>
<button type="button" value="3" onclick='numberPressed(this);updateText()'>3</button>
<button type="button" value="4" onclick='numberPressed(this);updateText()'>4</button>
<button type="button" value="5" onclick='numberPressed(this);updateText()'>5</button>
<button type="button" value="6" onclick='numberPressed(this);updateText()'>6</button>
<button type="button" value="7" onclick='numberPressed(this);updateText()'>7</button>
<button type="button" value="8" onclick='numberPressed(this);updateText()'>8</button>
<button type="button" value="9" onclick='numberPressed(this);updateText()'>9</button>
<br><br>
<button type="button" id="add">+</button>
<button type="button" id="sub">-</button>
<button type="button" id="mul">*</button>
<button type="button" id="div">/</button><br><br>
<button type="button" id="enter">CALCULATE</button>
<button type="button" id="clear">CLEAR</button>

Related

Javascript for card shuffle failing

Over my head with javascript. I'm trying to get the cards to shuffle when clicking next.
Currently, it moves forward with one random shuffle and stops. Back and forward buttons then no longer work at that point.
Please help—many thanks.
When I'm lost and unsure what sample of the code to pinpoint, the captions go up to 499. The sample is also here: https://rrrhhhhhhhhh.github.io/sentences/
Very new to javascript. So any help is greatly appreciated. Very open to better ways to achieve this???
How I have it set up:
HTML:
var r = -1;
var mx = 499; // maximum
var a = new Array();
function AddNumsToDict(){
var m,n,i,j;
i = 0;
j = 0;
while (i <= 499)
{
m = (500 * Math.random()) + 1;
n = Math.floor(m);
for (j=0;j<=499;j++)
{
if (a[j] == (n-1))
{
j = -1;
break;
}
}
if (j != -1)
{
//a.push(n-1);
a[i] = (n-1);
i++;
j=0;
}
}
return;
}
function startup()
{
writit('SENTENCES<br><br><br>Robert Grenier', 'test');
SetCookie("pg", -1);
AddNumsToDict();
}
function SetCookie(sName, sValue)
{
document.cookie = sName + "=" + escape(sValue) + ";"
}
function GetCookie(sName)
{
// cookies are separated by semicolons
var aCookie = document.cookie.split("; ");
for (var i=0; i < aCookie.length; i++)
{
// a name/value pair (a crumb) is separated by an equal sign
var aCrumb = aCookie[i].split("=");
if (sName == aCrumb[0])
return unescape(aCrumb[1]);
}
// a cookie with the requested name does not exist
return null;
}
function doBack(){
//var oPrev = xbElem('prev');
//var oNxt = xbElem('nxt');
//if ((oNxt) && (oPrev))
//{
var num = GetCookie("pg");
if (num == mx){ //maximum
SetCookie("pg",parseInt(num) - 1);
num = GetCookie("pg");
}
// oNxt.disabled = false;
// if (num <= 1){
// oPrev.disabled = true;
// }
if (num >= 1){
num--;
writit(Caption[a[num]], 'test');
SetCookie("pg",num);
}
//}
}
function doNext(){
//var oPrev = xbElem('prev');
//var oNxt = xbElem('nxt');
// if ((oNxt) && (oPrev))
// {
var num = GetCookie("pg");
// if (num > -1){
// oPrev.disabled = false;
// }
// else{
// oPrev.disabled = true;
// }
// if (num >= parseInt(mx)-1){ //maximum - 1
// oNxt.disabled = true;
// }
// else {
// oNxt.disabled = false;
// }
if (num <= parseInt(mx)-2){
num++;
writit(Caption[a[num]],'test');
SetCookie("pg",num);
}
// }
}
function writit(text,id)
{
if (document.getElementById)
{
x = document.getElementById(id);
x.innerHTML = '';
x.innerHTML = text;
}
else if (document.all)
{
x = document.all[id];
x.innerHTML = text;
}
else if (document.layers)
{
x = document.layers[id];
l = (480-(getNumLines(text)*8))/2;
w = (764-(getWidestLine(text)*8))/2;
text2 = '<td id=rel align="center" CLASS="testclass" style="font:12px courier,courier new;padding-left:' + w.toString() + 'px' + ';padding-top:' + l.toString() + 'px' + '">' + text + '</td>';
x.document.open();
x.document.write(text2);
x.document.close();
}
}
function getNumLines(mystr)
{
var a = mystr.split("<br>")
return(a.length);
}
function getWidestLine(mystr)
{
if (mystr.indexOf(" ") != -1)
{
re = / */g;
mystr = mystr.replace(re,"Z");
//alert(mystr);
}
if (mystr.indexOf("<u>") != -1)
{
re = /<u>*/g;
mystr = mystr.replace(re, "");
re = /<\/u>*/g;
mystr = mystr.replace(re, "");
}
if (mystr.indexOf("<br>") != -1)
{
var ss, t;
var lngest;
ss = mystr.split("<br>");
lngest = ss[0].length;
for (t=0; t < ss.length; t++)
{
if (ss[t].length > lngest)
{
lngest = ss[t].length;
}
}
}
else {
lngest = mystr.length;
}
return(lngest);
}
// -->
</script>
<body bgcolor="gainsboro" onload="startup();">
<table bgcolor="white" border height="480px" width="764px" cellpadding="0" cellspacing="0">
<tr>
<td align="center">
<table nowrap>
<tr>
<td><img width="700px" height="1px" src="./resources/images/w.gif"></td>
<td>
<div class="testclass" id="test"></div>
</td>
</tr>
</table>
</td>
</tr>
</table>
<center>
<form>
<p>
<input type="button" onclick="doBack(); return false" value="Back">
<input type="button" onclick="doNext(); return false" value="Next">
JS:
var _____WB$wombat$assign$function_____ = function(name) {return (self._wb_wombat && self._wb_wombat.local_init && self._wb_wombat.local_init(name)) || self[name]; };
if (!self.__WB_pmw) { self.__WB_pmw = function(obj) { this.__WB_source = obj; return this; } }
{
let window = _____WB$wombat$assign$function_____("window");
let self = _____WB$wombat$assign$function_____("self");
let document = _____WB$wombat$assign$function_____("document");
let location = _____WB$wombat$assign$function_____("location");
let top = _____WB$wombat$assign$function_____("top");
let parent = _____WB$wombat$assign$function_____("parent");
let frames = _____WB$wombat$assign$function_____("frames");
let opener = _____WB$wombat$assign$function_____("opener");
function CaptionArray(len) {
this.length=len
}
Caption = new CaptionArray(499);
Caption[0] = "leaf and the ants as latterly"
Caption[1] = "thought<br>living in<br>Davis would<br>be ok"
Caption[2] = "sure arm today"
Caption[3] = "AMY<br><br>no we<br>both do<br>different<br>songs together"
Caption[4] = "much of anything she doesn't like that at all"
Caption[5] = "SUNG AS LAKE<br><br><br>that never wanted back to come"
Caption[6] = "five sound shut doors"
Caption[7] = "oh<br>my nose is<br>so<br>red<br>Obediah<br>dear"
Caption[8] = "these<br>cubes<br>have been<br>on the floor"
Caption[9] = "sweating importunate"
Caption[10] = "all over noises phone rings"
Caption[11] = "I think this is the water supply for Lake Johnsbury"
Caption[12] = "Paw so greasy"
Caption[13] = "BLACK & WHITE RAIN<br><br><br>clear water grey drops<br><br><br>on windshields in a line<br><br><br>of cars progressing slowly<br><br><br>with windshield wipers wiping"
Caption[14] = "EMILY<br><br>Roger,<br><br>are you<br><br>thinking of me"
Caption[15] = "STICKS<br><br><br>rhythm is inside the sound like another"
Caption[16] = "I think their dog always barks when coming back from the woods"
Caption[17] = "weren't there<br><br>conversations"
Caption[18] = "LOOKING AT FIRE<br><br><u>ashes</u> to ashes<br><br>looking at the fire<br><br>at has been added"
Caption[19] = "a the bank"
}

Dom Modification to clear Radio Button Info with Reset Button

So I have made a form that I can clear with a reset button. On this form, I have four radio buttons (that code is towards the top). When a button is selected, info comes up using "displayText".
<script type="text/javascript">
function textToDisplay (radioValue) {
console.log("textToDisplay + " + radioValue);
var displayText = "";
if (radioValue == "S") {
displayText = "Shortboards are under 7 ft in length.";
}
else if (radioValue == "L") {
displayText = "Longboards are usually between 8 and 10 ft.";
}
if (radioValue == "A") {
displayText = "Alternative boards defy easy aesthetic description.";
}
if (radioValue == "M") {
displayText = "Mid-Length surfboards are between 7 and 8 ft.";
}
return (displayText)
}
//DOM modification
function modifyDom(radioInput) {
console.log(radioInput.name + " + " + radioInput.value);
var displayText = textToDisplay(radioInput.value);
console.log(node);
var insertnode = document.getElementById("radioButtons");
var infonode = document.getElementById("info")
if (infonode === null) {
console.log("infonode does not yet exist");
var node = document.createElement("DIV");
node.setAttribute("id", "info");
node.className = "form-text infoText";
var textnode = document.createTextNode(displayText);
node.appendChild(textnode);
console.log(node);
insertnode.appendChild(node);
}
else {
console.log("infonode already exists");
infonode.innerHTML = displayText;
}
}
function checkboxesSelected (checkboxes, errorString) {
console.log("checkboxesSelected function");
var cbSelected = 0;
for (i=0; i<checkboxes.length; i++) {
if (checkboxes[i].checked) {
cbSelected += 1;
}
}
if (cbSelected < 2) {
return (errorString);
} else {
return "";
}
}
function validate (form) {
console.log("validate form");
var fail = "";
fail += checkboxesSelected(form.extras, "At least TWO fin setup needs
to be selected.\n")
if (fail == "") return true
else { alert(fail); return false }
}
</script>
When I reset my page using the button,
<input type="reset" name="reset" value="Reset">
the buttons themselves are cleared but the information that appeared from selecting the button is still visible. How can I reset the page so the displayText information is not visible? Thanks!
You can use an event listener for the reset event generated by clicking the reset button to execute cleanup code.
Here's a cut down example of the technique:
"use strict";
let myForm = document.getElementById("myForm");
let infoNode = document.getElementById("infonode");
let infoText = {
"S": "small board's are good",
"L": "large board's are good too"
};
myForm.addEventListener("change", function (event) {
if(event.target.name == "size") {
infoNode.innerHTML = infoText[ event.target.value];
}
}, false);
myForm.addEventListener("reset", function (event) {
infoNode.innerHTML = "";
}, false);
<form id="myForm">
<label> <input name="size" type="radio" value = "S"> Short</label><br>
<label> <input name="size" type="radio" value = "L"> Long</label><br>
<input type="reset" value="reset">
</form>
<div id="infonode"></div>
would suggest to remove the dynamically attached div#info:
document.getElementById("info").remove();
or blank it:
document.getElementById("info").innerHTML = "";

Javascript toLocaleString onKeyUp Event

I need some help to fix this issue, I'm trying to print out value from <input> tag while typing, and it should print out with thousand separator, but it return number like I input, more precisely it doesn't work. How I have to fix this...?
function cDes(e) {
var k = e.currentTarget;
var prc = k.value; //example value: 123456789
var prc_f = prc.toLocaleString('de-DE');
var oDiv = document.getElementById('cOut');
if (e.keyCode == 13) {
if (prc.length < 1) {
oDiv.innerHTML = 'FREE';
} else {
oDiv.innerHTML = prc_f; //expected output value: 123.456.789
}
} else {
oDiv.innerHTML = '...';
}
}
<input type='number' id='price' onKeyUp='cDes(event)'>
<div id='cOut'></div>
Convert the input string to Number before using Number.toLocaleString():
var prc_f = Number(prc).toLocaleString('de-DE');
Example:
// get a reference to the element once
var oDiv = document.getElementById('cOut');
function cDes(e) {
var prc = e.target.value; //example value: 123456789
if (e.keyCode == 13) {
if (prc.length < 1) {
oDiv.innerHTML = 'FREE';
} else {
// you only need to convert the input when you display it
oDiv.innerHTML = Number(prc).toLocaleString('de-DE'); //expected output value: 123.456.789
}
} else {
oDiv.innerHTML = '...';
}
}
<input type='number' id='price' onKeyUp='cDes(event)'>
<div id='cOut'></div>
This answer may deviate a little from your expectation , but you if objective is to show the price along with symbol , you can use Intl.NumberFormat
function cDes(e) {
var k = e.currentTarget;
var prc = k.value; //example value: 123456789
var prc_f = nf.format(prc);
var oDiv = document.getElementById('cOut');
if (e.keyCode == 13) {
if (prc.length < 1) {
oDiv.innerHTML = 'FREE';
} else {
oDiv.innerHTML = prc_f; //expected output value: 123.456.789
}
} else {
oDiv.innerHTML = '...';
}
}
var nf = new Intl.NumberFormat('de-DE', {
style: 'currency',
currency: 'EUR',
minimumFractionDigits: 0,
maximumFractionDigits: 2
});
<input type='number' id='price' onKeyUp='cDes(event)'>
<div id='cOut'></div>

Basic Javascript onclick

here's my code, brand new to coding trying to get the box "points" to return the sum of pointSum if "Ben" is typed into the box "winner". Just trying to work on some basics with this project. Attempting to make a bracket of sorts
<HTLML>
<head>
<script>
var pointSum = 0;
var firstRound = 20;
var secondRound = 50;
var thirdRound = 100;
var fourthRound = 150;
var fifthRound = 250;
var finalRound = 300;
var winnerOne = false;
var winnerTwo = false;
var winnerThree = false;
var winnerFour = false;
var winnerFive = false;
var winnerSix = false;
if (winnerOne = true){
pointSum+=firstRound
} else if (winnerTwo = true){
pointSum+=secondRound
} else if (winnerThree = true){
pointSum+=thirdRound
} else if (winnerFour = true){
pointSum+=fourthRound
} else if (winnerFive = true){
pointSum+=fifthRound
} else if (winnerSix = true){
pointSum+=finalRound
else
function tally() {if document.getElementById('winner') == "Ben" { winnerOne = true;
}
pointSum=document.getElementById("points").value;
}
</script>
</head>
<body>
<form>
Winner:
<input type="text" name="winner" id="winner" size="20">
Points:
<input type="text" name="points" id="points" size="20">
Submit
<button type= "button" onclick="tally()">Tally points</button>
</form>
</body>
</html>
UPDATE***** new code, getting better, not returning console errors but still not getting anything in the "points" box upon clicking tally
<HTLML>
<head>
<script>
var pointSum = 0;
var firstRound = 20;
var secondRound = 50;
var thirdRound = 100;
var fourthRound = 150;
var fifthRound = 250;
var finalRound = 300;
var winnerOne = false;
var winnerTwo = false;
var winnerThree = false;
var winnerFour = false;
var winnerFive = false;
var winnerSix = false;
function tally() {
var winner = document.getElementById("winner").value;
var firstWinner = "Ben";
if (winner == firstWinner){
winnerOne == true;
}
pointSum = document.getElementById("points").value;
}
if (winnerOne == true){
pointSum+=firstRound;
} else if (winnerTwo){
pointSum+=secondRound;
} else if (winnerThree){
pointSum+=thirdRound;
} else if (winnerFour){
pointSum+=fourthRound;
} else if (winnerFive){
pointSum+=fifthRound;
} else if (winnerSix){
pointSum+=finalRound;
}
</script>
</head>
<body>
<form>
Winner:
<input type="text" name="winner" id="winner" size="20">
Points:
<input type="text" name="points" id="points" size="20">
Submit
<button type= "button" onclick="tally()">Tally points</button>
</form>
<div class="updatePoints">
</div>
</body>
</html>
Your code has a few mistakes, lets change it a little bit!
First, you need to access 'value' atribbute of your winner element in your if statement, and surround all the statement in parenthesis
function tally() {
if (document.getElementById('winner').value == "Ben"){
winnerOne = true;
}
pointSum = document.getElementById("points").value;
}
Second, you use '==' to make comparison, you are using '=', it means that you are assign true to variables, and you're forgetting to put ';' at the end of lines! change this part:
if (winnerOne == true){
pointSum+=firstRound;
}
put all of your if/else like the example above!
Hint: when you are using if statement you can use like this:
if (winnerOne){ //you can omit == true, because if winnerOne is true, it will enter ind the if statement
//will enter here if winnerOne is true
}
if (!winnerOne){ //you can omit == false, because if winnerOne is not true, it will enter ind the if statement
//will enter here if winnerOne is false
}
You also have a left over else at the end of your if check which is invalid. You need to end the last else if statement with the };.
Are you trying to out put the text somewhere? I don't see any code that is handling this - you may want to add some HTML that will update like so:
<div class="updatePoints">
// leave empty
</div>
Then within your JavaScript you can always add some code to update the .updatePoints
var points = document.getElementByClass('updatePoints');
points.innerHTML = pointSum.value;
Have add some lines in your code and modify it with some comments. Can try at https://jsfiddle.net/8fhwg6ou/. Hope can help.
<HTLML>
<head>
<script>
var pointSum = 0;
var firstRound = 20;
var secondRound = 50;
var thirdRound = 100;
var fourthRound = 150;
var fifthRound = 250;
var finalRound = 300;
var winnerOne = false;
var winnerTwo = false;
var winnerThree = false;
var winnerFour = false;
var winnerFive = false;
var winnerSix = false;
function tally() {
var winner = document.getElementById("winner").value;
var firstWinner = "Ben";
if (winner == firstWinner){
winnerOne = true; // Use only one = symbol to assign value, not ==
pointSum = Number(document.getElementById("points").value); // moved from outside and convert to number
// This code will update point in Points box
document.getElementById("points").value = tally_pointsum(pointSum);
// The codes below will add the text in div, just remove the + sign if you don't like
document.getElementById("updatePoints").innerHTML += (tally_pointsum(pointSum) - pointSum) + " points added<br />";
}
}
// Wrap codes below become a function, lets call it tally_pointsum:
function tally_pointsum(pointSum) {
if (winnerOne == true){
pointSum+=firstRound;
} else if (winnerTwo){
pointSum+=secondRound;
} else if (winnerThree){
pointSum+=thirdRound;
} else if (winnerFour){
pointSum+=fourthRound;
} else if (winnerFive){
pointSum+=fifthRound;
} else if (winnerSix){
pointSum+=finalRound;
}
return pointSum; //return the sum to caller
}
</script>
</head>
<body>
<form>
Winner:
<input type="text" name="winner" id="winner" size="20">
Points:
<input type="text" name="points" id="points" size="20">
Submit
<button type= "button" onclick="tally()">Tally points</button>
</form>
<!-- change class="updatePoints" to id="updatePoints" for document.getElementById("updatePoints") -->
<div id="updatePoints">
</div>
Happy coding.

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