for loop printing only last item in array of objects - javascript

Guys i am in a trouble here. I made a table of songs, then i inserted them in local storage, and now i want to search the items in local storage to see if a name of an album exists in local storage(in a table) or not, i made this .js code and when i try to search for items in local storage(objects in array), for example i try searching for california and it prints "NO" but there is one in local storage called california, but when i search for chuck it prints "YES", and if i add one more it will do the same, it will print only the last item in this array, why is this happening. Thanks in advance.
let ls = [{
name: "california",
artist: "blink182",
year: 2016,
num: 28
},
{
name: "chuck",
artist: "sum41",
year: 2004,
num: 13
}
];
localStorage.setItem("songs", JSON.stringify(ls));
document.getElementById("btn").addEventListener("click", search);
function search(e) {
JSON.parse(localStorage.getItem("songs"));
let inputVal = document.getElementById("input").value;
let outputVal = document.getElementById("output");
for (let i = 0; i < ls.length; i++) {
if (inputVal === ls[i].name) {
outputVal.innerHTML = "YES";
} else {
outputVal.innerHTML = "NO";
}
}
e.preventDefault();
}
body {
background-color: lime;
line-height: 1.5;
font-size: 15px;
margin: auto;
width: 80%;
}
table,
th,
td {
border: 2px solid black;
padding: 20px;
}
div {
margin: 50px;
}
<table>
<tr>
<th>Name of album</th>
<th>Artist</th>
<th>Year</th>
<th>numOfTracks</th>
</tr>
<tr>
<td>California</td>
<td>Blink 182</td>
<td>2016</td>
<td>28</td>
</tr>
<tr>
<td>Chuck</td>
<td>Sum 41</td>
<td>2004</td>
<td>13</td>
</tr>
</table>
<form id="myForm">
<p>Search LS</p>
<input type="text" id="input">
<button type="submit" id="btn">Search</button>
</form>
<div id="output"></div>

The problem is that you're setting the HTML of the div to YES/NO. Which is being overridden in the next iteration that's why you feel like it's printing for the last item in the list. Instead you need to append to what's already there
for (let i = 0; i < ls.length; i++) {
if (inputVal === ls[i].name) {
outputVal.innerHTML = outputVal.innerHTML + " YES" ;
} else {
outputVal.innerHTML = outputVal.innerHTML + " NO";
}
}
Now you should be able to see YESNO for the list values

function search(e) {
JSON.parse(localStorage.getItem("songs"));
let inputVal = document.getElementById("input").value;
let outputVal = document.getElementById("output");
var resultExists = false;
var resultCount = 0;
for (let i = 0; i < ls.length; i++) {
if (inputVal === ls[i].name) {
// Case 2
resultExists = true;
resultCount++;
// Updated your case
// outputVal.innerHTML = "YES";
// break;
}
//else {
// outputVal.innerHTML = "NO";
//}
}
// Case 2
if(resultExists){
outputVal.innerHTML = "YES";
// Do anithing with resultCount if you need
}else{
outputVal.innerHTML = "NO";
}
e.preventDefault();
}

It's printing all the items but you are overwriting the innerHTML value each time instead of adding to it, see the edit below.
let ls = [{
name: "california",
artist: "blink182",
year: 2016,
num: 28
},
{
name: "chuck",
artist: "sum41",
year: 2004,
num: 13
}
];
// localStorage.setItem("songs", JSON.stringify(ls));
document.getElementById("btn").addEventListener("click", search);
function search(e) {
// JSON.parse(localStorage.getItem("songs"));
let inputVal = document.getElementById("input").value;
let outputVal = document.getElementById("output");
/* note the use of += instead of = */
for (let i = 0; i < ls.length; i++) {
if (inputVal === ls[i].name) {
outputVal.innerHTML += "YES";
} else {
outputVal.innerHTML += "NO";
}
}
e.preventDefault();
}
body {
background-color: lime;
line-height: 1.5;
font-size: 15px;
margin: auto;
width: 80%;
}
table,
th,
td {
border: 2px solid black;
padding: 20px;
}
div {
margin: 50px;
}
<table>
<tr>
<th>Name of album</th>
<th>Artist</th>
<th>Year</th>
<th>numOfTracks</th>
</tr>
<tr>
<td>California</td>
<td>Blink 182</td>
<td>2016</td>
<td>28</td>
</tr>
<tr>
<td>Chuck</td>
<td>Sum 41</td>
<td>2004</td>
<td>13</td>
</tr>
</table>
<form id="myForm">
<p>Search LS</p>
<input type="text" id="input">
<button type="submit" id="btn">Search</button>
</form>
<div id="output"></div>

I would try something like this:
function search(e) {
let songs = JSON.parse(localStorage.getItem("songs"));
let inputVal = document.getElementById("input").value;
let outputVal = document.getElementById("output");
outputVal.innerHTML = dataContainsField(ls, inputVal) ? "YES" : "NO";
e.preventDefault();
}
function dataContainsField(data, field) {
for (let i = 0; i < data.length; i++) {
if (field === data[i].name) return true;
}
return false;
}
Putting the logic to check for the existence of the data in your dataset into a function makes it easier to code and decouples that logic from your search function.

As you're using for loop that's why every time it is just overwriting you value with last value. You can try like this with Array.prototype.find(). Also you've some issue with your localStorage data parsing inside your search(e) function, here you're not storing it to ls variable before doing any find/search operation
See working demo https://jsfiddle.net/ttr80ona/
let ls = [{name: "california",artist: "blink182",year: 2016,num: 28},{name: "chuck",artist: "sum41",year: 2004,num: 13}];
localStorage.setItem("songs", JSON.stringify(ls));
document.getElementById("btn").addEventListener("click", search);
function search(e) {
let ls = JSON.parse(localStorage.getItem("songs")); //I've modified here
let inputVal = document.getElementById("input").value;
let outputVal = document.getElementById("output");
var status = ls.find(elm => elm.name === inputVal);
if (status)
outputVal.innerHTML = "YES";
else
outputVal.innerHTML = "NO";
e.preventDefault();
}

The problem is you are overriding yes with no. You should set default to false and make it true once found or remove else condition.
function search(e) {
JSON.parse(localStorage.getItem("songs"));
let inputVal = document.getElementById("input").value;
let outputVal = document.getElementById("output");
let bFound = false;
for (let i = 0; i < ls.length; i++) {
if(inputVal === ls[i].name) {
bFound = true;
break;
}
}
outputVal.innerHTML = bFound ? "YES" : "No";
e.preventDefault();
}

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

How to save multiple user inputs into new variables

Im creating a guessing game and the user has 5 attempts to make the correct guess. I want to save their previous guesses (inputs) to show it to them. I have been using the snippet below to save one attempt when the user types into an <input> field, but how can I save the next 4 attempts in new variables such as userGuess2, userGuess3, etc.
var userGuess = document.getElementById("inputField").value;
$('#previousGuesses').text(userGuess);
Ok then let's pretend this is your input
<input type="text" id="inputField">
You can create an index that will increment everytime the users presses enter to save another answer
var i=1;
And the id name your autogenerated spans will have
var name = "previousGuesses";
Now on your function you will save the value when the user presses enter like you described and when that happens it will create a new span element where it will display the value stored
function myFunction(){
$("#inputField").keypress(function( event ) {
if ( event.which == 13 || event.which == 9) {
var userGuess = document.getElementById("inputField").value;//get value of the answer
var span = document.createElement('SPAN');//create a new span
span.innerHTML = userGuess + "<br>";//answer value goes here
span.id = name+i;//this is the id of your new span, remember ids are unique so we attach var i to the name var we declared before
document.body.appendChild(span);
//$('#previousGuesses'+i).text(userGuess);
i++;
}
});
}
now call your function
myFunction();
https://jsfiddle.net/kenpy/m16bojhg/4/
You can just simply add an element for the user's last attempts and add to it.
f(guessCount === 1) {
guesses.textContent = 'Previous guesses: ';
}
guesses.textContent += userGuess + ' ';
var randomNumber = Math.floor(Math.random() * 100) + 1;
var guesses = document.querySelector('.guesses');
var lastResult = document.querySelector('.lastResult');
var lowOrHi = document.querySelector('.lowOrHi');
var guessSubmit = document.querySelector('.guessSubmit');
var guessField = document.querySelector('.guessField');
var guessCount = 1;
var resetButton;
guessField.focus();
function checkGuess() {
var userGuess = Number(guessField.value);
if(guessCount === 1) {
guesses.textContent = 'Previous guesses: ';
}
guesses.textContent += userGuess + ' ';
if(userGuess === randomNumber) {
lastResult.textContent = "Good job! You win!";
lastResult.style.backgroundColor = 'green';
lowOrHi.textContent = '';
setGameOver();
} else if(guessCount === 10) {
lastResult.textContent = 'Hahaha You suck!';
lowOrHi.textContent = '';
setGameOver();
} else {
lastResult.textContent = "Oops! You're Wrong!";
lastResult.style.backgroundColor = 'red';
if(userGuess < randomNumber) {
lowOrHi.textContent = 'Last guess was too low!';
} else if(userGuess > randomNumber) {
lowOrHi.textContent = 'Last guess was too high!';
}
}
guessCount++;
guessField.value = '';
guessField.focus();
}
guessSubmit.addEventListener('click', checkGuess);
console.log('cheat is: ' + randomNumber);
function setGameOver() {
guessField.disabled = true;
guessSubmit.disabled = true;
resetButton = document.createElement('button');
resetButton.textContent = 'Play Again?';
document.body.appendChild(resetButton);
resetButton.addEventListener('click', resetGame);
}
function resetGame() {
guessCount = 1;
var resetParas = document.querySelectorAll('.resultParas p');
for(var i = 0 ; i < resetParas.length ; i++) {
resetParas[i].textContent = '';
}
resetButton.parentNode.removeChild(resetButton);
guessField.disabled = false;
guessSubmit.disabled = false;
guessField.value = '';
guessField.focus();
lastResult.style.backgroundColor = 'white';
randomNumber = Math.floor(Math.random() * 100) + 1;
}
body{
background-image: linear-gradient(to left top, #c6fced, #a3efda, #7fe3c7, #54d5b3, #00c89f);
color: #2F3139;
margin: 10rem auto;
height:50vh;
}
h1 {
font-size: 1.5rem;
}
.lastResult {
color: white;
padding: 3px;
}
button {
margin-left:3rem ;
}
<h3 class="display-4 text-center text-muted text-capitalize"></h3>
<div class="container">
<div class="row">
<div class="col-md-6 ">
<h1 class="text-muted text-capitalize">
<span class="text-primary">JavaScript</span> Number guessing game</h1>
<p class="lead">Simply enter a number between 1 - 100 then click the button</p>
</div>
<div class="col-md-6">
<div class="mt-4 d-inline-block">
<div class="form">
<label for="guessField">Guess a number : </label><input type="text" id="guessField" class="guessField">
<input type="submit" value="Submit guess" class="guessSubmit">
</div>
<div class="resultParas text-center lead">
<p class="guesses"></p>
<p class="lastResult"></p>
<p class="lowOrHi"></p>
</div>
</div>
</div> </div>
</div>
Resource
JavaScript number guessing game

I want to add items from js generated product table to cart table but I don't how to tell the system what table row am selecting

I'm still trying to find a way to get the addToCart() function to work.
fetch('server.php')
.then((res) => res.json())
.then((response) => {
let output = '';
for (let i in response) {
output += `<tr>
<td>${response[i].quantity}</td>
<td><button>${response[i].productName}</button></td>
<td>₦${response[i].price}.00</td>
<td><button id="go" onclick="addToCart()">+1</button></td>
<td><input type="text"></td>
</tr>`;
}
document.querySelector('.tbody').innerHTML = output;
})
.catch((error) => console.log(error));
function addToCart() {
document.getElementById('fillUp').innerHTML += '<tr><td>123</d></tr>';
console.log(val);
}
<!-- Product Table -->
<table id="myTable">
<thead class="tHeadRow">
<th>Quantity</th>
<th>Products</th>
<th>Price</th>
</thead>
<tbody class="tbody"></tbody>
</table>
<!-- Cart Table -->
<div class="cart">
<h3>Checkout Cart</h3>
<div class="cartContent">
<table class="cartTable">
<tbody id="fillUp"></tbody>
<tfoot>
<tr>
<td style="font-weight: bold">Total:</td>
<td style="font-weight: bold"></td>
</tr>
</tfoot>
</table>
</div>
</div>
<!--- I got a possible solution but when I tried it, I got Uncaught --->
<!--- TypeError: Cannot read properties of null (reading 'rows') --->
var tbody = document.getElementById('tbody'),rIndex;
var tb = tbody.rows.length;
for(var i = 0; i < tb; i++) {
tbody.rows[i].onclick = function() {
console.log(this.cells[0].innerHTML);
}
Dropping a row into another table was accomplished mainly by cloneNode() and the original row was removed by .remove(). In the OP code:
var tbody = document.getElementById('tbody'),rIndex;
This makes very little sense. There is no tag with an id of #tbody there's a tag with a class of .tbody which at the very least can be accessed by .querySelector() that's why it's null.
The problem will run into as I see it is that you are using an inline event handler:
onclick="addToCart()"
Inline event handlers are garbage. Use on event properties and/or event listeners, read the following after reviewing the example below:
Events
Event Delegation
HTMLFormElement
const allTables = document.querySelectorAll('table');
const shop = allTables[0].tBodies[0];
const cart = allTables[1].tBodies[0];
fetch('https://my.api.mockaroo.com/i_mart.json?key=3634fcf0')
.then((res) => res.json())
.then((response) => {
let output = '';
for (let i in response) {
output += `<tr id='R${i}'>
<td><button name='itm' class='itm' type='button'>${response[i].item}</button></td>
<td>₦${response[i].price.substring(1)}</td>
<td><input name='qty' class='qty' value='${response[i].quantity}' readonly>
<input name='def' value='${response[i].quantity}' type='hidden'>
</td>
<td><input name='cnt' class='cnt' value='0' readonly><button name="add" class='btn add' type='button' disabled>+1</button>
<button name="sub" class='btn sub' type='button' disabled>-1</button>
</td>
<td><input name='subT' class='subT' value='₦0.00' readonly></td>
</tr>`;
}
shop.innerHTML = output;
})
.catch((error) => console.log(error));
const itemTo = (row, dest) => {
const copy = row.cloneNode(true);
row.remove();
dest.appendChild(copy);
const btns = copy.querySelectorAll('.btn');
const fields = copy.querySelectorAll('input');
if (dest === cart) {
btns[0].disabled = false;
} else {
btns.forEach(btn => btn.disabled = true);
fields[0].value = fields[1].value;
fields[2].value = '0';
fields[3].value = '₦0.00';
}
};
const addToSubFrom = (row, dir) => {
let D = dir === undefined ? 1 : dir;
const cells = row.children;
let add = row.querySelector('.add');
let sub = row.querySelector('.sub');
let prc = cells[1].textContent.substring(1);
let qty = cells[2].firstElementChild;
let cnt = cells[3].firstElementChild;
let subT = cells[4].firstElementChild;
let c = +cnt.value + D;
if (c === 0) {
sub.disabled = true;
} else {
sub.disabled = false;
}
let q = +qty.value - D;
if (q === 0) {
add.disabled = true;
} else {
add.disabled = false;
}
let p = +prc;
let sT = ((p * 100) * c) / 100;
cnt.value = c;
qty.value = q;
subT.value = '₦' + sT.toFixed(2);
};
const getTotal = array => array.map(inp => +inp.value.substring(1) * 100).reduce((sum, cur) => sum + cur);
const addToCart = e => {
const io = e.currentTarget.elements;
const btn = e.target;
if (btn.matches('button')) {
let row = document.querySelector('#' + btn.closest('tr').id);
let S;
switch (btn.name) {
case 'itm':
let dest = btn.closest('tbody').className === 'shop' ? cart : shop;
itemTo(row, dest);
S = [...io.subT];
io.total.value = (getTotal(S) / 100).toFixed(2);
break;
case 'add':
S = [...io.subT];
addToSubFrom(row);
io.total.value = (getTotal(S) / 100).toFixed(2);
break;
case 'sub':
S = [...io.subT];
addToSubFrom(row, -1);
io.total.value = (getTotal(S) / 100).toFixed(2);
break;
default:
break;
}
}
e.stopPropagation();
};
const UI = document.forms[0];
UI.onclick = addToCart;
:root {
font: 1ch/1.5 'Segoe UI'
}
body {
font-size: 3ch;
}
table {
table-layout: fixed;
border-collapse: collapse;
width: 100%;
}
caption {
font-size: 2rem;
font-weight: 900
}
.h1 {
width: 35%;
}
.h3 {
width: 20%;
}
.h3 {
width: 10%;
}
.h4 {
width: 20%;
text-align: left;
}
.h5 {
width: 15%;
}
td:nth-of-type(n+2) {
text-align: center;
}
tfoot th {
text-align: right;
}
input,
output {
display: inline-block;
font-size: 100%;
line-height: 1.15;
}
input,
output,
td:nth-of-type(2) {
font-family: Consolas
}
button {
font-size: 1.25rem;
cursor: pointer;
}
output {
font-weight: 900;
}
.qty,
.cnt,
.subT {
width: 2ch;
border: 0;
}
.subT {
width: 6ch
}
<!-- Product Table -->
<form>
<table>
<caption>
iMart™ Online Wholesale
</caption>
<thead>
<th class='h1'>Item</th>
<th class='h2'>Price</th>
<th class='h3'>Qty</th>
<th class='h4'>Count</th>
<th class='h5'>SubTotal</th>
</thead>
<tbody class='shop'></tbody>
</table>
<!-- Cart Table -->
<table>
<caption>Checkout Cart</caption>
<thead>
<th class='h1'>Item</th>
<th class='h2'>Price</th>
<th class='h3'>Qty</th>
<th class='h4'>Count</th>
<th class='h5'>SubTotal</th>
</thead>
<tbody class='cart'></tbody>
<tfoot>
<tr>
<th colspan='4'>Total: ₦</th>
<td><output id='total'></output></td>
</tr>
</tfoot>
</table>
</form>

HTML Input doesn't allow double digits to be typed in from keyboard

I'm making a basic calculator and so far it "works". Users can only enter in a single digit from their keyboard. If they want to use double digits they're going to have to use the arrows in the text box. How can I make it so that users can enter in double digit numbers? If the user tries to type in double digit numbers the second number only get stored (so typing in 25 will only store 5)
// Base Variables
let result = 0;
let numb1 = 0;
let numb2 = 0;
let firstNumberEntered = false;
//This will be rewritten
let calculationDescription = `${numb1} + ${numb2}`;
document.querySelector('#input-number').addEventListener('keypress', numbersInput);
function numbersInput(e) {
if (!firstNumberEntered && e.key === 'Enter') {
numb1 = document.getElementById("input-number").value;
firstNumberEntered = true;
document.getElementById("input-number").innerHTML = "";
} else if (firstNumberEntered && e.key === 'Enter') {
numb2 = document.getElementById("input-number").value;
firstNumberEntered = false;
console.log(`${numb1} and ${numb2}`);
}
document.getElementById("input-number").value = "";
}
document.querySelector("#btn-add").addEventListener('click', sumNumbs);
document.querySelector("#btn-subtract").addEventListener('click', subtractNumbs);
document.querySelector("#btn-multiply").addEventListener('click', multiplyNumbs);
document.querySelector("#btn-divide").addEventListener('click', divideNumbs);
function sumNumbs() {
let numb1Final = parseInt(numb1);
let numb2Final = parseInt(numb2);
result = numb1Final + numb2Final;
calculationDescription = `${numb1} + ${numb2}`;
outputResult(result, calculationDescription);
}
function subtractNumbs() {
let numb1Final = parseInt(numb1);
let numb2Final = parseInt(numb2);
result = numb1Final - numb2Final;
calculationDescription = `${numb1} - ${numb2}`;
outputResult(result, calculationDescription);
}
function multiplyNumbs() {
let numb1Final = parseInt(numb1);
let numb2Final = parseInt(numb2);
result = numb1Final * numb2Final;
calculationDescription = `${numb1} x ${numb2}`;
outputResult(result, calculationDescription);
}
function divideNumbs() {
let numb1Final = parseInt(numb1);
let numb2Final = parseInt(numb2);
result = numb1Final / numb2Final;
calculationDescription = `${numb1} / ${numb2}`;
outputResult(result, calculationDescription);
}
<section id="calculator">
<input type="number" id="input-number" />
<div id="calc-actions">
<button type="button" id="btn-add">+</button>
<button type="button" id="btn-subtract">-</button>
<button type="button" id="btn-multiply">*</button>
<button type="button" id="btn-divide">/</button>
</div>
</section>
All this does is grab the elements on the HTML page and put them into variables and send info back to be displayed
const userInput = document.getElementById('input-number');
const addBtn = document.getElementById('btn-add');
const subtractBtn = document.getElementById('btn-subtract');
const multiplyBtn = document.getElementById('btn-multiply');
const divideBtn = document.getElementById('btn-divide');
const currentResultOutput = document.getElementById('current-result');
const currentCalculationOutput = document.getElementById('current-calculation');
function outputResult(result, text) {
currentResultOutput.textContent = result;
currentCalculationOutput.textContent = text;
}
Not sure if providing my CSS is necessary, but let me know and I'll make a change.
I just started learning JavaScript recently. I watched a few videos on a Udemy tutorial on doing this project, but I stopped watching and tried to figure the rest out myself.
What I did try doing was adding maxlength="6" to my HTML input element, but that didn't work.
function numbersInput(e) {
if(!firstNumberEntered && e.key === 'Enter') {
numb1 = document.getElementById("input-number").value;
firstNumberEntered = true;
document.getElementById("input-number").innerHTML = "";
document.getElementById("input-number").value = "";
}
else if(firstNumberEntered && e.key === 'Enter') {
numb2 = document.getElementById("input-number").value;
firstNumberEntered = false;
console.log(`${numb1} and ${numb2}`);
document.getElementById("input-number").value = "";
}
}
Add document.getElementById("input-number").value = "";
to the end of both if statements and remove from the end of the function
Here's my own basic calculator using HTML, CSS, and javascript only.
To be able to input one or more digit numbers, use arrays to function as storage of those numbers chosen and for your chosen arithmetic operation as well.
please see my source code for a clearer grasp of my idea.
//index.html
<!DOCTYPE html>
<html>
<head>
<title>My HTML/CSS/JS Calculator</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
<div class="outer-container">
<div class="items" id="items"></div>
<div class="calc-screen">
<div id="screen"></div>
</div>
<div class="keys-container">
<button type="button" class="keys" id="opm" onclick="opm()">*</button>
<button type="button" class="keys" id="opd" onclick="opd()">/</button>
<button type="button" class="keys" id="opa" onclick="opa()">+</button>
<button type="button" class="keys" id="ops" onclick="ops()">-</button>
<button type="button" class="keys" id="num9" onclick="num9()">9</button>
<button type="button" class="keys" id="num8" onclick="num8()">8</button>
<button type="button" class="keys" id="num7" onclick="num7()">7</button>
<button type="button" class="keys" id="num6" onclick="num6()">6</button>
<button type="button" class="keys" id="num5" onclick="num5()">5</button>
<button type="button" class="keys" id="num4" onclick="num4()">4</button>
<button type="button" class="keys" id="num3" onclick="num3()">3</button>
<button type="button" class="keys" id="num2" onclick="num2()">2</button>
<button type="button" class="keys" id="num1" onclick="num1()">1</button>
<button type="button" class="keys" id="num0" onclick="num0()">0</button>
<button type="button" class="keys" id="del" onclick="del()">Del</button>
<button type="button" class="keys" id="clr" onclick="clr()">Clr</button>
<button type="submit" class="keys" id="equals" onclick='equals()'>=</button>
</div>
</div>
<script type="text/javascript" src="js/js.js"></script>
</body>
</html>
//js.js
var item1, op, item2, arr1, arr2, text, x, prod, qout, sum, diff, a, b, c;
item1, item2, op = '';
arr1 = [];
arr2 = [];
function num9() {
if (op=='') {
arr1.push(document.getElementById("num9").innerHTML);
arr1Function();
}
else {
arr2.push(document.getElementById("num9").innerHTML);
arr2Function();
}
}
function num8() {
if (op=='') {
arr1.push(document.getElementById("num8").innerHTML);
arr1Function();
}
else {
arr2.push(document.getElementById("num8").innerHTML);
arr2Function();
}
}
function num7() {
if (op=='') {
arr1.push(document.getElementById("num7").innerHTML);
arr1Function();
}
else {
arr2.push(document.getElementById("num7").innerHTML);
arr2Function();
}
}
function num6() {
if (op=='') {
arr1.push(document.getElementById("num6").innerHTML);
arr1Function();
}
else {
arr2.push(document.getElementById("num6").innerHTML);
arr2Function();
}
}
function num5() {
if (op=='') {
arr1.push(document.getElementById("num5").innerHTML);
arr1Function();
}
else {
arr2.push(document.getElementById("num5").innerHTML);
arr2Function();
}
}
function num4() {
if (op=='') {
arr1.push(document.getElementById("num4").innerHTML);
arr1Function();
}
else {
arr2.push(document.getElementById("num4").innerHTML);
arr2Function();
}
}
function num3() {
if (op=='') {
arr1.push(document.getElementById("num3").innerHTML);
arr1Function();
}
else {
arr2.push(document.getElementById("num3").innerHTML);
arr2Function();
}
}
function num2() {
if (op=='') {
arr1.push(document.getElementById("num2").innerHTML);
arr1Function();
}
else {
arr2.push(document.getElementById("num2").innerHTML);
arr2Function();
}
}
function num1() {
if (op=='') {
arr1.push(document.getElementById("num1").innerHTML);
arr1Function();
}
else {
arr2.push(document.getElementById("num1").innerHTML);
arr2Function();
}
}
function num0() {
if (op=='') {
arr1.push(document.getElementById("num0").innerHTML);
arr1Function();
}
else {
arr2.push(document.getElementById("num0").innerHTML);
arr2Function();
}
}
function opm() {
if (arr1=='') {
document.getElementById("screen").innerHTML = "Please press a number first!";
}
else if (op!='' && arr2!='') {
console.log("press equal sign");
}
else {
document.getElementById("screen").innerHTML = document.getElementById("opm").innerHTML;
op = '*';
console.log(op);
}
}
function opd() {
if (arr1=='') {
document.getElementById("screen").innerHTML = "Please press a number first!";
}
else if (op!='' && arr2!='') {
console.log("press equal sign");
}
else {
document.getElementById("screen").innerHTML = document.getElementById("opd").innerHTML;
op = '/';
console.log(op);
}
}
function opa() {
if (arr1=='') {
document.getElementById("screen").innerHTML = "Please press a number first!";
}
else if (op!='' && arr2!='') {
console.log("press equal sign");
}
else {
document.getElementById("screen").innerHTML = document.getElementById("opa").innerHTML;
op = '+';
console.log(op);
}
}
function ops() {
if (arr1=='') {
document.getElementById("screen").innerHTML = "Please press a number first!";
}
else if (op!='' && arr2!='') {
console.log("press equal sign");
}
else {
document.getElementById("screen").innerHTML = document.getElementById("ops").innerHTML;
op = '-';
console.log(op);
}
}
function equals() {
a = parseInt(item1); b = parseInt(item2);
if (op == '*') {
prod = a * b;
document.getElementById("items").innerHTML = a+' '+op+' '+b+' =';
c = prod;
document.getElementById("screen").innerHTML = c;
console.log('product: '+c);
result(c);
}
else if (op == '/') {
qout = a / b;
document.getElementById("items").innerHTML = a+' '+op+' '+b+' =';
c = qout;
document.getElementById("screen").innerHTML = c;
console.log('qoutient: '+c);
result(c);
}
else if (op == '+') {
sum = a + b;
document.getElementById("items").innerHTML = a+' '+op+' '+b+' =';
c = sum;
document.getElementById("screen").innerHTML = c;
console.log('sum: '+c);
result(c);
}
else if (op == '-') {
diff = a - b;
document.getElementById("items").innerHTML = a+' '+op+' '+b+ ' =';
c = diff;
document.getElementById("screen").innerHTML = c;
console.log('difference: '+c);
result(c);
}
else {
document.getElementById("screen").innerHTML = "Please press a number first!";
}
}
function result() {
console.log('function result: '+c);
arr1=[]; arr2=[]; item1, item2, op = '';
item1 = c;
console.log('function result new item1: '+item1);
arr1.push(item1);
arr1Function();
}
function del() {
if (arr1!='' && op=='' && arr2=='') {
arr1.pop();
console.log(arr1);
arr1Function();
}
else if (arr1!='' && op!='' && arr2=='') {
op = '';
document.getElementById("screen").innerHTML = op;
}
else if (arr1!='' && op!='' && arr2!='') {
arr2.pop();
console.log(arr2);
arr2Function();
}
}
function clr() {
arr1=[]; arr2=[]; item1,item2,op='';
console.log(arr1+', '+op+', '+arr2+', '+item1+', '+item2);
document.getElementById("screen").innerHTML = '';
document.getElementById("items").innerHTML = '';
}
function arr1Function() {
document.getElementById("screen").innerHTML = arr1;
text = ""; arr1.forEach(myFunction); text += "";
function myFunction(value) {
text += value;
x = parseInt(text);
document.getElementById("screen").innerHTML = x;
item1 = x;
console.log("Arr 1 Parse: "+x);
console.log("Arr 1: "+arr1);
console.log("Item 1: "+item1);
}
}
function arr2Function() {
document.getElementById("screen").innerHTML = arr2;
text = ""; arr2.forEach(myFunction); text += "";
function myFunction(value) {
text += value;
x = parseInt(text);
document.getElementById("screen").innerHTML = x;
item2 = x;
console.log("Arr 2 Parse: "+x);
console.log("Arr 2: "+arr2);
console.log("Item 2: "+item2);
}
}
//css
body {
background-color: orange;
}
.outer-container {
position: static;
background-color: black;
margin: auto;
border: solid black 2px;
width: 350px;
padding: 20px;
box-sizing: border-box;
border-radius: 20px;
}
.items {
background-color: silver;
border: solid white 1px;
display: inline-block;
color: black;
max-width: 100%;
font-size: 16px;
height: 20px;
box-sizing: border-box;
}
.calc-screen {
padding: 10px;
border: solid white 1px;
max-width: 100%;
width: 100%;
height: 50px;
background-color: silver;
color: white;
font-size: 25px;
box-sizing: border-box;
overflow-x: auto;
}
.keys-container {
margin-top: 20px;
width: 100%;
border: solid white 1px;
max-width: 100%;
display: inline-block;
}
#equals {
width: 100%;
}
.keys {
float: left;
border: solid black 1px;
box-sizing: border-box;
width: 25%;
height: 40px;
box-sizing: border-box;
text-align: center;
margin: auto;
font-size: 25px;
padding: 5px;
}
.keys:hover {
background-color: blue;
color: white;
}

Why doesn't my script work with checkboxes?

I am trying to make a little "game" and for some reason, if I try and get the checked of a checkbox, my script will flip out... sometimes it works, sometimes it just stops executing. Is there some sort of an error I missed?
<html>
<head>
<title>Untitled Document</title>
<script>
var check = "showcheck";
var number = 1234;
var lvl = 1;
var oldlvl = 1;
var multiplier = 10000;
var start = 1;
function exefunction() {
document.getElementById("boxv").focus();
if (check == "showcheck") {
document.getElementById("message").innerHTML = "What was the number?";
document.getElementById("num").style.display = "none";
document.getElementById("box").style.display = "inline";
document.getElementById("boxv").focus();
check = "checknum";
}
else if (check == "checknum") {
if (document.getElementById("boxv").value == number) {
document.getElementById("message").innerHTML = "CORRECT!";
document.getElementById("boxv").style.color = "#00DD00";
document.getElementById("boxv").value = number;
document.getElementById("level").innerHTML = "Level: " + lvl;
lvl++;
}
else if (document.getElementById("boxv").value != number) {
document.getElementById("message").innerHTML = "INCORRECT!";
document.getElementById("boxv").style.color = "#DD0000";
document.getElementById("boxv").value = number;
document.getElementById("level").innerHTML = "Level: " + lvl;
if (lvl>1) {lvl--;}
loselife();
}
check = "showmem";
}
else if (check == "showmem") {
if (lvl == oldlvl + 10) {
oldlvl = lvl;
multiplier = multiplier * 10;
document.getElementById("boxv").maxLength = multiplier.toString().length - 1;
}
else if (lvl < oldlvl) {
oldlvl = lvl - 10;
multiplier = multiplier / 10;
document.getElementById("boxv").maxLength = multiplier.toString().length - 1;
}
number = Math.floor(Math.random() * multiplier / 10 * 9) + multiplier / 10;
document.getElementById("boxv").style.color = "#000000";
document.getElementById("boxv").value = "";
document.getElementById("message").innerHTML = "Memorize this number: ";
document.getElementById("num").innerHTML = number;
document.getElementById("num").style.display = "inline";
document.getElementById("box").style.display = "none";
check = "showcheck";
}
}
function loselife(){
var life = 4;
var hearts = "♥ ";
alert(document.getElementById("lifebox").checked);
}
function submitenter() {
var keycode = window.event.keyCode;
if (keycode == 13) {
if (start === 0) {exefunction();}
else {startfunc();}
}
if (keycode < 47 || keycode > 58) {
return false;
}
}
function startfunc() {
document.getElementById("button").innerHTML = '<input name="" type="button" value="OK" onClick="exefunction()"/>';
document.getElementById("level").innerHTML = "Level: " + lvl;
document.getElementById("message").innerHTML = "Memorize this number: ";
document.getElementById("num").style.display = "inline";
document.getElementById("boxv").value = "";
document.getElementById("box").style.display = "none";
if (document.getElementById("lifecheck").checked === true) {
document.getElementById("life").innerHTML = "♥ ♥ ♥ ♥ ♥ ";
}
else if (document.getElementById("lifecheck").checked === false) {
document.getElementById("life").innerHTML = "";
}
if (document.getElementById("timercheck").checked === true) {
document.getElementById("timer").innerHTML = "3:00";
}
else if (document.getElementById("timercheck").checked === false) {
document.getElementById("timer").innerHTML = "";
}
start = 0;
}
function tests() {
alert(lfckv);
}
</script>
<style type="text/css">
#level, #life, #timer{
color: #666;
}
* {
text-align: center;
}
#num {
display: none;
}
#num {
font-size: x-large;
}
#body {
margin-top: 250px;
margin-right: auto;
margin-bottom: 100px;
margin-left: auto;
}
body {
background-color: #6FF;
}
</style></head>
<body onKeyPress="return submitenter()" >
<div id="body">
<span id="level"></span>
<table align="center">
<tr>
<td width="200" height="50" align="center" valign="middle"><span id="message">What level would you like to begin at?</span></td>
<td width="200" height="50" align="center" valign="middle"><span id="num">1234</span><span id="box"><input type="text" id="boxv" maxlength="4" value="1"/></span></td>
</tr>
</table>
<table align="center">
<tr>
<td width="200" id="life"><label><input id="lifecheck" type="checkbox" >Lives</label></td>
<td id="button"><input type="button" value="OK" onClick="startfunc()"/></td>
<td width="200" id="timer"><label><input id="timercheck" type="checkbox" >Timer</label></td>
</tr>
</table>
<input name="" type="button" onClick="tests()" value="tests()">
</div>
</body>
</html>
lifebox isnt defined in the loselife() function. Plus, also check the test() function, that alert() statement has a variable that isnt defined.
If you are using Google chrome (or any other browser that can help you debug), I would suggest you to debug through your lines of code.
I think you're better off using simple equality for checking the state of your checkboxes, because I'm pretty the outcome is not a Boolean.
So it would be something like that :
if (document.getElementById("lifecheck").checked == true) {
or simply
if (document.getElementById("lifecheck").checked) {
instead of
if (document.getElementById("lifecheck").checked === true) {
Ahah! I figured out the problem. Apparently, when I set the visibility of the checkbox to none, it also set the checkvalue to null for some reason. I had expected it to keep the checkvalue, but for some reason it does not.

Categories