All buttons only affect one input instead of respective input - javascript

I am making a little project for my self. So basically its main function is to create a base counter for each game.
For example: If there are two players it should create three bases. (This is for the card game "smash up" if that helps you understand better.) But when the Buttons populate they all only effect the last input. I can not figure out how to make them effect their respective inputs.
The problem I am having is that every button I click only effects the last input.
<html>
<title> Base Maker </title>
<body>
<div>
<hl> Score Keeper </h1>
<hr>
<input type = "text" placeholder = "How many players?">
<button id = "enter" onclick = "baseMaker()">
Enter
</button>
</div>
<p></p>
</body>
</html>
var parent = document.querySelector("p");
var input = document.querySelector("input");
var enter = document.getElementById("enter");
function baseMaker()
{
for(var i = 0; i <= input.value; i++)
{
//base
var base = document.createElement("p");
base.textContent = "Base " + (i + 1) + ":";
//score
var score = document.createElement( "input");
score.setAttribute("id", "score" + i);
score.value = 20;
//upbutton
var upButton = document.createElement( "button");
upButton.textContent = "+";
upButton.setAttribute("id", "upButton" + i)
upButton.addEventListener('click', function() {
score.value++; });
//downbutton
var downButton = document.createElement( "button");
downButton.textContent = "-";
downButton.setAttribute("id", "downButton" + i)
downButton.addEventListener('click', function() {
score.value--; });
//populate data
parent.appendChild(base);
parent.appendChild(score);
parent.appendChild(upButton);
parent.appendChild(downButton);
}
input.value = "";
}

This is a common thing to run into especially when not using a framework in javascript.
I am not sure why this happens but when a function is defined directly in a loop, the closure for these created functions becomes whatever it is after the last iteration. I believe it is because the closure for each callback function is only "sealed up" (for lack of a better word) at the end of the loop-containing-function's execution which is after the last iteration. It's really beyond me, though.
There are some easy ways to avoid this behavior:
use bind to ensure a callback gets called with the correct input (used in solution at bottom)
create a function which creates a handler function for you and use that in the loop body
function createIncrementHandler(input, howMuch){
return () => input.valueAsNumber += howMuch;
}
/// then in your loop body:
downButton.addEventListener('click', createIncrementHandler(score, 1));
get the correct input by using the event parameter in the handler
downButton.addEventListener('click', (event) => event.target.valueAsNumber += 1);
make the entire body of the loop into a function, for example:
function createInputs(i) {
//base
var base = document.createElement("p");
base.textContent = "Base " + (i + 1) + ":";
//score
var score = document.createElement("input");
score.type = "number";
score.setAttribute("id", "score" + i);
score.value = 20;
//upbutton
var upButton = document.createElement( "button");
upButton.textContent = "+";
upButton.setAttribute("id", "upButton" + i)
upButton.addEventListener('click', function() {
score.value++; });
//downbutton
var downButton = document.createElement( "button");
downButton.textContent = "-";
downButton.setAttribute("id", "downButton" + i)
downButton.addEventListener('click', function() {
score.value--; });
//populate data
parent.appendChild(base);
parent.appendChild(score);
parent.appendChild(upButton);
parent.appendChild(downButton);
}
Here is a full example of one of the possible fixes.
<html>
<title> Base Maker </title>
<body>
<div>
<hl> Score Keeper </h1>
<hr>
<input type="text" placeholder="How many players?">
<button id="enter" onclick="baseMaker()">
Enter
</button>
</div>
<p></p>
<script>
var parent = document.querySelector("p");
var input = document.querySelector("input");
var enter = document.getElementById("enter");
function incrementInput(input, byHowMuch) {
input.valueAsNumber = input.valueAsNumber + byHowMuch;
}
function baseMaker() {
for (var i = 0; i <= input.value; i++) {
//base
var base = document.createElement("p");
base.textContent = "Base " + (i + 1) + ":";
//score
var score = document.createElement("input");
score.type = "number";
score.setAttribute("id", "score" + i);
score.value = 20;
//upbutton
var upButton = document.createElement("button");
upButton.textContent = "+";
upButton.setAttribute("id", "upButton" + i)
upButton.addEventListener('click', incrementInput.bind(null, score, 1));
//downbutton
var downButton = document.createElement("button");
downButton.textContent = "-";
downButton.setAttribute("id", "downButton" + i)
downButton.addEventListener('click', incrementInput.bind(null, score, -1));
//populate data
parent.appendChild(base);
parent.appendChild(score);
parent.appendChild(upButton);
parent.appendChild(downButton);
}
input.value = "";
}
</script>
</body>
</html>

I will do that this way :
const
AllBases = document.querySelector('#bases')
, bt_Start = document.querySelector('#game-go')
, bt_newGame = document.querySelector('#new-game')
, playerCount = document.querySelector("#play-start > input")
;
playerCount.value = ''
playerCount.focus()
playerCount.oninput = () =>
{
playerCount.value.trim()
bt_Start.disabled = (playerCount.value === '' || isNaN(playerCount.value))
playerCount.value = (bt_Start.disabled) ? ''
: (playerCount.valueAsNumber > playerCount.max) ? playerCount.max
: (playerCount.valueAsNumber < playerCount.min) ? playerCount.min
: playerCount.value
}
bt_newGame.onclick = () =>
{
playerCount.value = ''
playerCount.disabled = false
bt_Start.disabled = true
bt_newGame.disabled = true
AllBases.innerHTML = ''
playerCount.focus()
}
bt_Start.onclick = () =>
{
playerCount.disabled = true
bt_Start.disabled = true
bt_newGame.disabled = false
for(let i = 0; i <= playerCount.valueAsNumber; i++)
{
let base = document.createElement('p')
base.countValue = 20 // create a counter property on <p>
base.innerHTML = `Base ${i+1} : <span>${base.countValue}</span> <button>+</button> <button>−</button>\n`
AllBases.appendChild(base)
}
}
AllBases.onclick = ({target}) =>
{
if (!target.matches('button')) return // verify clicked element
let countElm = target.closest('p')
if (target.textContent==='+') countElm.countValue++
else countElm.countValue--
countElm.querySelector('span').textContent = countElm.countValue
}
#bases p span {
display : inline-block;
width : 6em;
border-bottom : 2px solid aqua;
padding-right : .2em;
text-align : right;
margin : 0 .3em;
}
#bases p button {
width : 2em;
margin : 0 .1em;
cursor : pointer;
}
<hr>
<hl> Score Keeper </h1>
<hr>
<div id="play-start" >
<input type="number" placeholder="How many players?" min="2" max="4">
<button id="game-go" disabled> Enter </button>
<button id="new-game" disabled> new </button>
</div>
<hr>
<div id="bases"></div>
If it helps, I can add more explanations

Related

Draw in two tables vanilla JS

I am working with program that will randomly choose who is making a Christmas gift to whom.
I've created an empty array. When you add a "player" it's pushing the name into two different arrays. Players[] and Players2[].
When you start a draw. The program writes the names of the Players[] on the left hand side and on the right side it writes the drawn names from Players2[].
Every Player from Players2[], after being drawn, is being deleted from the array so in the end we have an empty Players2[] array and full Players[] array.
The problem is: I can't make a working if statement that is checking if the person will not draw himself...
let Players = [];
let Players2 = [];
const addBTN = document.getElementById('addBTN');
const onlyLetters = /^[a-zżźćóęśńłA-ZŻŹĆÓŁĘŚŃŁ ]+$/;
const refreshBTN = document.getElementById('refreshBTN');
const warningBTNyes = document.getElementById('warning-button-yes');
const warningBTNno = document.getElementById('warning-button-no');
const playersList = document.getElementById('playersList');
const playersList2 = document.getElementById('playersList2');
const startBTN = document.getElementById('startBTN');
const drawLotsBTN = document.getElementById('drawLotsBTN');
addBTN.addEventListener('click', function() {
const input = document.getElementById('addPLAYER');
const person = document.getElementById('addPLAYER').value;
if (input.value == "") {
console.log('error_empty_input');
document.getElementById('errorMSG').style.color = "red";
document.getElementById('errorMSG').innerHTML = "Wpisz imię osoby!";
} else if (input.value.match(onlyLetters)) {
console.log('good');
Players.push(person);
Players2.push(person);
playersList.innerHTML = playersList.innerHTML + "<br>" + person;
document.getElementById('addPLAYER').value = "";
document.getElementById('errorMSG').style.color = "green";
document.getElementById('errorMSG').innerHTML = "Powodzenie! Dodaj kolejną osobę.";
} else {
console.log('error_input');
document.getElementById('errorMSG').style.color = "red";
document.getElementById('errorMSG').innerHTML = "Coś jest nie tak z imieniem. Pamiętaj aby wprowadzać same litery!";
}
});
refreshBTN.addEventListener('click', function() {
document.getElementById('warning').style.display = "block";
});
warningBTNyes.addEventListener('click', function() {
location.reload(true);
document.getElementById('addPLAYER').value = "";
});
warningBTNno.addEventListener('click', function() {
document.getElementById('warning').style.display = "none";
});
startBTN.addEventListener('click', function() {
drawLotsBTN.disabled = false;
const input = document.getElementById('addPLAYER');
const person = document.getElementById('addPLAYER').value;
if (input.value == "") {
} else if (input.value.match(onlyLetters)) {
console.log('good');
Players.push(person);
Players2.push(person);
playersList.innerHTML = playersList.innerHTML + "<br>" + person;
document.getElementById('addPLAYER').value = "";
document.getElementById('errorMSG').style.color = "green";
document.getElementById('errorMSG').innerHTML = "Powodzenie! Zaczynasz losowanie!";
} else {
console.log('error_input');
document.getElementById('errorMSG').style.color = "red";
document.getElementById('errorMSG').innerHTML = "Coś jest nie tak z imieniem. Pamiętaj aby wprowadzać same litery!";
}
document.getElementById('addPLAYER').disabled = true;
});
drawLotsBTN.addEventListener('click', function() {
for (let i = 0; i = Players2.length; i++) {
if (Players2.length > 0) {
randomPerson = Math.floor(Math.random() * Players2.length);
if (randomPerson != Players.indexOf(i)) {
console.log(Players2[randomPerson]);
playersList2.innerHTML = playersList2.innerHTML + "<br>" + Players2[randomPerson];
Players2.splice(randomPerson, 1);
}
} else {
console.log('error_empty_array');
}
}
});
<div id="warning" class="warning">
<div class="warning-flex">
<h1>Wszelkie wpisane imiona zostaną usunięte</h1>
<div class="warning-buttons">
<button id="warning-button-yes" class="warning-button-yes">Tak</button>
<button id="warning-button-no" class="warning-button no">Nie</button>
</div>
</div>
</div>
<div class="lotteryContainer">
<div class="left">
<p>dodaj osobę</p>
<div class="addPerson">
<input required id="addPLAYER" type="text">
<button id="addBTN">+</button>
<p id="errorMSG"></p>
<div class="refresh">
<button id="refreshBTN">Od nowa</button>
<button id="startBTN">Start</button>
</div>
</div>
</div>
<div class="right">
<p>Uczestnicy</p>
<div class="tables">
<div class="tableLeft">
<p id=playersList></p>
</div>
<div class="tableRight">
<p id="playersList2"></p>
</div>
</div>
<button id="drawLotsBTN">Losuj</button>
</div>
</div>
<script src="app.js"></script>
Now if I understand what your program aims to do, there is a simple algorithm for it.
How I understand your goal:
You have a list of persons who are going to give presents to each other. (like in secret Santa). It is random who will give to who, but each person gives and receives one gift.
How to implement it (i'd normaly use maps, but I am guessing you are more comfortable with arrays):
players = ["Adam", "Bret", "Clay", "Donald"];
players.sort(function(a, b){return 0.5 - Math.random()}); // shuffles array
gives_to = [...players]; // copy values of array
gives_to.push(gives_to.shift()); // let the first element be the last
Here the first player (players[0]) will give to gives_to[0] and the second to gives_to[1] etc.
I've created this JS script trying to use Trygve Ruud algorithm but it doesn't work like desired.
drawLotsBTN.addEventListener('click', function(){
if(Players.length > 0) {
console.log(Players)
Players.sort(function(a, b){
return 0.5 - Math.random();
});
for(let i = 0; i < Players.length; i++){
playersList2.innerHTML = playersList2.innerHTML + "<br>" + Players[i];
}
}
else{
console.log('error_empty_array');
}
});

Getting an Uncaught TypeError: Cannot set property 'onclick' of null with <script> at the end

I've looked at previous questions like this and cannot find the answer to my problem. I am working in javascript creating a checkout screen and I have two onclicks for two different html files but when I go to the html file for both it says that the other onclick is null. I have tried window.load and moving the script to the bottom of the
var cart = [];
var search = document.getElementById("addItem");
let placement = 0;
var cartElement = document.getElementById("showCart");
var cartTotal = document.getElementById("totalCart");
search.onclick = function(e) {
var userInput = document.getElementById("query").value;
var cartHTML = "";
e.preventDefault();
placement = 0;
for (i = 0; i < menu.length; i++) {
if (menu[i][0].includes(userInput)) {
cart.push(menu[i]);
placement++;
}
}
if (placement == 0) {
alert("Menu option not included. Please try again.");
}
cart.forEach((item, Order) => {
var cartItem = document.createElement("span");
cartItem.textContent = item[0] + " (" + item[1] + ")";
cartHTML += cartItem.outerHTML;
});
cartElement.innerHTML = cartHTML;
}
window.onload = function() {
var checkout = document.getElementById("addCartButton");
checkout.onclick = function(event) {
cart.forEach()
var cartTotalHTML = "";
event.preventDefault();
cart.forEach(Item, Order => {
var totalInCart = 0;
var writeCart = document.createElement("span");
totalInCart += Order[1];
});
writeCart.textContent = cartTotal += item[1];
cartTotalHTML = writeCart.outerHTML;
cartTotal.innerHTML = cartTotalHTML;
console.log(cartTotal);
}
}
<h3>Search for items in the menu below to add to cart</h3>
<form id="searchMenu">
<input type="search" id="query" name="q" placeholder="Search Menu..."></inpuut>
<input type = "Submit" name= "search" id="addItem" ></input>
</form>
<h4>Your cart: </h4>
<div class="Cart">
<div id="showCart"></div>
</div>
<script src="Script.js"></script>
<h4>Cart</h4>
<button id='addCartButton' class="Cart">Add Cart</button>
<div class="ShowCart">
<div id="totalCart"></div>
</div>
<script src="Script.js"></script>

How to have a button that sorts and another button that reverses the word density of my text?

I don't want to have something like this because it's ugly to see:
But instead, I want my word density to get more organized and sorted out. How do I accomplish all this?
Sort from the highest word density first as a default.
Have a button to reverse (or have the lowest word density first).
And then another button that sorts the highest word density first (like the default).
Here's my HTML:
const displayText = () => {
const inputPage = document.getElementById("input-page");
const countPage = document.getElementById("count-page");
const text = document.getElementById("text");
const textValue = text.value;
if (text.value !== "") {
// normal flow will continue if the text-area is not empty
inputPage.style.display = "none";
document.getElementById("display-text").innerText = textValue;
countPage.style.display = "block";
} else {
// if the text-area is empty, it will issue a warning.
alert("Please enter some text first.");
}
const countWords = (str) => {
return str.split(" ").length;
};
const wordCount = countWords(textValue);
const renderWordCount = () => {
const wordCountDiv = document.getElementById("word-count");
wordCountDiv.innerHTML = "<h1> Words Counted: " + wordCount + "</h1>";
};
const getWordDensity = (str) => {
let wordList = {};
str.split(/[\s.,—–]+/).forEach((word) => { // '\s.,—–' removes space or tab, periods, commas, em and en dashes from the text.
if (typeof wordList[word] == "undefined") {
wordList[word] = 1;
} else {
wordList[word]++;
}
});
return wordList;
};
const wordDensity = getWordDensity(textValue);
const renderWordDensity = () => {
const wordDensityDiv = document.getElementById("word-density");
let table = "<table>";
for (let word in wordDensity) {
table +=
"<tr><td>" + word + "</td><td>" + wordDensity[word] + "</td></tr>";
}
table += "</table>";
wordDensityDiv.innerHTML = "<h1> Word Density: </h1>" + table;
};
renderWordCount();
renderWordDensity();
};
<!DOCTYPE html>
<html>
<head>
<title>Word Counter</title>
</head>
<body>
<div id="input-page">
<h1>Word Counter</h1>
<form action="">
<textarea id="text" type="text" rows="22" cols="60"></textarea>
<br />
</form>
<button onclick="displayText()">COUNT</button>
</div>
<div id="count-page" style="display: none;">
<h1>Your Text:</h1>
<p id="display-text"></p>
<div id="word-count"></div>
<div id="word-density"></div>
</div>
</body>
</html>
Thanks a lot in advance!
You are not going to be able to sort your words correctly, because you are are storing them in an object. Instead store them in an array like this:
wordList = [
{
word: "the",
count: 5,
},{
word: "pizza",
count: 2,
},
]
When you store the data like that, you can sort the array using a custom sort function:
const highestFirst = true;
wordList.sort( (a,b) => {
if( a.count == b.count ) return 0;
if( highestFirst )
return (a.count < b.count) ? -1 : 1;
else
return (a.count > b.count) ? -1 : 1;
});
So have your button run the above function to sort the array, then loop through the array, and for each print out the row. Something like:
var table = document.createElement('table');
wordList.forEach( w => {
let tr = document.createElement('tr');
let td1 = document.createElement('td');
let td2 = document.createElement('td');
td1.innerText = w.word;
td2.innerText = w.count;
tr.appendChild(td1);
tr.appendChild(td2);
table.appendChild(tr);
});

How to remove array objects from localStorage using dynamic buttons? [JS only]

New to JS here, been struggling with this one for a few hours now.
So I created a to do list with a button that stores objects in an array inside localStorage and also creates dynamic list items with content and delete buttons. Whenever I click the delete button it removes the dynamic list item but doesn't remove it from localStorage. I can't figure out how to assign each button to the specific array index in localStorage.
https://codepen.io/jupiterisland/pen/ooPXWV
var taskList = []; //build array
if(localStorage.taskList){ //call func to recreate li's on refresh
taskList = JSON.parse(localStorage.taskList) || [];
createTasks(taskList)
}
function submitFunc() {
var task = { //build objects
desc: document.getElementsByTagName("textarea")[0].value,
date: document.getElementsByTagName("input")[0].value,
time: document.getElementsByTagName("input")[1].value,
important: document.getElementsByTagName("input")[1].checked
};
if(task.desc && task.date !== ""){
taskList[taskList.length] = task; //put objects inside array
localStorage.taskList = JSON.stringify(taskList); //store array with stringify
newTaskList = JSON.parse(localStorage.taskList); //retrieve array with parse
createTasks(newTaskList)
document.getElementById("error").style.display = "none";
return false; //prevent submit
} else {
document.getElementById("error").style.display = "block";
document.getElementById("error").innerHTML = "Please enter a task description and a date.";
return false;
}
}
function createTasks (newTaskList){
for (i = 0; i < newTaskList.length; i++) { // display objects in list items
var currentTask = newTaskList[i];
var taskIndex = newTaskList.indexOf(currentTask);
newElement();
function newElement() {
var liNode = document.createElement("li");
var titleNode = document.createElement("h3");
var dNode = document.createElement("p");
var tNode = document.createElement("p");
var delNode = document.createElement("button")
liNode.className = "liNode";
titleNode.className = "titleNode";
dNode.className = "dNode";
tNode.className = "tNode";
delNode.className = "delete";
delNode.innerText = "Delete";
var titleText = newTaskList[i].desc;
var dateText = newTaskList[i].date;
var timeText = newTaskList[i].time;
var descNode = document.createTextNode(titleText);
var dateNode = document.createTextNode(dateText);
var timeNode = document.createTextNode(timeText);
titleNode.appendChild(descNode);
dNode.appendChild(dateNode);
tNode.appendChild(timeNode);
liNode.appendChild(titleNode);
liNode.appendChild(dNode);
liNode.appendChild(tNode);
liNode.appendChild(delNode);
document.getElementById("taskBoard").appendChild(liNode);
if (taskBoard.childElementCount > newTaskList.length) { //remove excess divs
for (n = 0; taskBoard.childElementCount - 2; n++) {
taskBoard.removeChild(taskBoard.firstChild);
}
}
function deleteTasks(){
var listItem = this.parentNode;
var ul = listItem.parentNode;
ul.removeChild(listItem);
}
delNode.addEventListener("click", deleteTasks);
}
}
}
<!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>Document</title>
</head>
<body>
<h1>My Task Board</h1>
<div class="container">
<form onsubmit="return submitFunc()">
<div>
<label for="">Task:</label>
<textarea name="name" rows="8" cols="80"placeholder="Please enter your task description"></textarea>
</div>
<div>
<label for="">Deadline:</label>
<input type="date" placeholder="Choose a date">
<input type="time" placeholder="Set time">
</div>
<div>
<label for="">Important:</label>
<input type="checkbox" name="" value="">
</div>
<button type="submit" name="button">Add Task</button>
<div id="error"></div>
</form>
</div>
<div>
<ul id="taskBoard"></ul>
</div>
</body>
</html>
var taskList = []; //build array
if(localStorage.taskList){ //call func to recreate li's on refresh
taskList = JSON.parse(localStorage.taskList) || [];
createTasks(taskList)
}
function fakeGuid() {
function s4() {
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
}
return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
s4() + '-' + s4() + s4() + s4();
}
function submitFunc() {
var task = { //build objects
desc: document.getElementsByTagName("textarea")[0].value,
date: document.getElementsByTagName("input")[0].value,
time: document.getElementsByTagName("input")[1].value,
important: document.getElementsByTagName("input")[1].checked,
id :fakeGuid()
};
if(task.desc && task.date !== ""){
taskList[taskList.length] = task; //put objects inside array
localStorage.taskList = JSON.stringify(taskList); //store array with stringify
newTaskList = JSON.parse(localStorage.taskList); //retrieve array with parse
createTasks(newTaskList)
document.getElementById("error").style.display = "none";
return false; //prevent submit
} else {
document.getElementById("error").style.display = "block";
document.getElementById("error").innerHTML = "Please enter a task description and a date.";
return false;
}
}
function createTasks (newTaskList){
for (i = 0; i < newTaskList.length; i++) { // display objects in list items
newElement(i);
function newElement(currentIndex) {
var liNode = document.createElement("li");
var titleNode = document.createElement("h3");
var dNode = document.createElement("p");
var tNode = document.createElement("p");
var delNode = document.createElement("button")
liNode.className = "liNode";
titleNode.className = "titleNode";
dNode.className = "dNode";
tNode.className = "tNode";
delNode.className = "delete";
delNode.innerText = "Delete";
var titleText = newTaskList[i].desc;
var dateText = newTaskList[i].date;
var timeText = newTaskList[i].time;
var descNode = document.createTextNode(titleText);
var dateNode = document.createTextNode(dateText);
var timeNode = document.createTextNode(timeText);
titleNode.appendChild(descNode);
dNode.appendChild(dateNode);
tNode.appendChild(timeNode);
liNode.appendChild(titleNode);
liNode.appendChild(dNode);
liNode.appendChild(tNode);
liNode.appendChild(delNode);
document.getElementById("taskBoard").appendChild(liNode);
if (taskBoard.childElementCount > newTaskList.length) { //remove excess divs
for (n = 0; taskBoard.childElementCount - 2; n++) {
taskBoard.removeChild(taskBoard.firstChild);
}
}
function deleteTasks(node, currentTask) {
var listItem = node.parentNode;
var ul = listItem.parentNode;
ul.removeChild(listItem);
taskList = taskList.filter(function(t) {
return t.id !== currentTask.id;
});
localStorage.taskList = JSON.stringify(taskList); //store array with stringify
}
var currentTask = newTaskList[currentIndex];
delNode.addEventListener("click", () => deleteTasks(delNode, currentTask));
}
}
}
Don't try to use index to manipulate DOM element. Instead use some kind of unique ID. In this case I created a fake GUID.
Read more on closure. The reason you are not able to pass index down to the function is because the index is bound to another context.
Any reason to stringify JSON for local storage? You can simply store an array.

Why does my value keep returning as "NaN"?

Here is the link to the jsbin.
I was almost finished with my project (I thought I was) and then I tested it out. It is supposed to add buttons with the chosen title of the task and the number of points it awards. Every time the button is clicked the points would be added on to the "Points" section and every 500 points my "Level" would increase.
Upon finishing it, it worked. Then I went to clear the localStorage since that's what I used to save the information, but I wanted to start over. When I did that, the 'Points' section, or 'results' value, keeps returning as "NaN". The code is exactly the same as it was when it worked. Can someone please tell me how to fix this problem, thank you in advance.
Here is the code. (Used bootstrap for CSS)
HTML
<center>
<br>
<h2> Add task </h2>
<div class='well' style='width:500px' id="addc">
<div id="addc">
<input class='form-control' style='width:450px' id="btnName" type="text" placeholder="New Task" /><br>
<input class='form-control' style='width:450px' id="btnPoints" type="text" placeholder="Points" /><br>
<button id="addBtn">Add</button>
</div> </div>
<div class='well' style='width:230px' id="container">
</div>
<hr style="width:400px;">
<h3>Points </h3>
<div id="result">0</div>
</div>
<hr style="width:400px;">
<div style="width:400px;">
<h3>Level
<p id='lvl'>0</p>
</div>
<hr style="width:400px;">
</center>
JavaScript
var res = document.getElementById('result');
res.innerText = localStorage.getItem('myResult');
var level = document.getElementById('lvl');
level.textContent = localStorage.getItem('myLevel');
var btns = document.querySelectorAll('.btn');
for(var i = 0; i < btns.length; i++) {
btns[i].addEventListener('click', function() {
addToResult(this.getAttribute('data-points'));
this.parentNode.removeChild(this.nextElementSibling);
this.parentNode.removeChild(this);
});
}
var addBtn = document.getElementById('addBtn');
addBtn.className = "btn btn-default";
addBtn.addEventListener('click', function() {
var container = document.getElementById('container');
var btnName = document.getElementById('btnName').value;
var btnPoints = parseInt(document.getElementById('btnPoints').value);
if(!btnName)
btnName = "Button ?";
if(!btnPoints)
btnPoints = 50;
var newBtn = document.createElement('button');
var newPnt = document.createElement('span');
newBtn.className = 'btn btn-danger';
newBtn.innerText = btnName;
newBtn.setAttribute('data-points', btnPoints);
newBtn.addEventListener('click', function() {
addToResult(this.getAttribute('data-points'));
this.parentNode.removeChild(this.nextElementSibling);
this.parentNode.removeChild(this);
});
newPnt.className = 'label';
newPnt.innerText = "+" + btnPoints;
container.appendChild(newBtn);
container.appendChild(newPnt);
});
function addToResult(pts) {
var result = document.getElementById('result');
result.innerText = parseInt(result.innerText) + parseInt(pts);
var lvl = 0;
var a = 100;
while (result.innerText > 5*a) {
lvl+=1;
a+=100;
}
document.getElementById('lvl').innerText = lvl;
var res = document.getElementById('result');
localStorage.setItem("myResult", res.innerText);
var level = document.getElementById('lvl');
localStorage.setItem("myLevel", level.textContent);
}
You were parsing result.innerText as a number, but its value, initially, was actually either NaN or nothing, both which end up being NaN. One fix is to just check if it parsed to a number, and if it didn't, fall back to 0.
I just basically changed that and removed some getElementByIds that, in my opinion, were redundant, check the addToResult function:
http://jsfiddle.net/owc26a0p/1/
function addToResult(pts) {
// NaN is falsy, so you can just use || to make a fallback to 0
var result = parseInt(resDiv.innerText, 10) || 0,
lvl = 0,
a = 100;
result = result + parseInt(pts, 10) || 0;
while (result > 5 * a) {
lvl += 1;
a += 100;
}
resDiv.innerText = result;
levelDiv.innerText = lvl;
localStorage.setItem("myResult", result);
localStorage.setItem("myLevel", levelDiv.textContent);
}
I ended up using jsFiddle since I couldn't always get jsBin to save my changes. Good luck.

Categories