Calculate total price in mutidimensional array - javascript

im trying to get the total price for a array of products but when i try it, it just return NaN
im kinda new to JavaScript so i might be doing it wrong
so i have a multidimensional array where i keed the data from the products then whit that data i create a table to display the data in the navigator but when i try to add all the price data to total it just say NaN in Navigator but i dont understand why because im using parseInt() method any idea why this could be happening? im running out of ideas to solve this.
JavaScript:
let carrito = [];
let continuar;
let figura;
let precio;
let cantidad;
let total;
do{
figura = prompt("Figura de acción:");
precio = prompt("Precio:");
cantidad = prompt("Cantidad:");
carrito.push([figura, cantidad, precio]);
continuar = prompt("¿Continuar?");
}while(continuar != "n");
console.log(carrito)
crearTabla()
function crearTabla(){
let tabla = "<thead><tr><th>Producto</th><th>Cantidad</th><th>Precio</th></tr></thead>"
for (var i = 0; i < carrito.length; i++) {
tabla += `<tr><td>${carrito[i][0]}</td><td>${carrito[i][1]}</td><td>${carrito[i][2]}</td></tr>`
total += parseInt(carrito[i][2]);
console.log(carrito[i][2]);
}
tabla += `<tr><td>---</td><td>Subtotal:</td><td>${total}</td></tr>`
document.getElementById("factura").innerHTML = tabla;
}
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Calculadora</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" href="css/style.css">
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<script src="js/app.js" defer></script>
<script src="https://cdn.jsdelivr.net/npm/#popperjs/core#2.10.2/dist/umd/popper.min.js" integrity="sha384-7+zCNj/IqJ95wo16oMtfsKbZ9ccEh31eOz1HGyDuCQ6wgnyJNSYdrPa03rtR1zdB" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/js/bootstrap.min.js" integrity="sha384-QJHtvGhmr9XOIpI6YVutG+2QOK9T+ZnN4kzFN1RtK3zEFEIsxhlmWl5/YESvpZ13" crossorigin="anonymous"></script>
</head>
<body>
<div>
<table id="factura"></table>
<button type="button" class="btn btn-success" onclick="calcular()">Calcular</button>
</div>
</body>
</html>

Initialize total as total = 0; - if you type undefined + 1 into the console of the browser dev tools it returns NaN. Without initializing total that is the result.
console.log(undefined + 1);
let total;
console.log('Total: ', total += 1);
let goodTotal = 0;
console.log('Good total: ', goodTotal += 1);

Related

How to make HTML table to Datatable?

I followed the below code to make a normal table into data table.. i included all the links responsible to make data table.. but still data table is not showing up.. pls resolve the error anyone?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ASSESSMENT 2</title>
<link rel="stylesheet" href="style.css">
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script src="https://cdn.datatables.net/1.12.1/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.12.1/js/dataTables.bootstrap4.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.2/css/bootstrap.css">
<link rel="stylesheet" href="https://cdn.datatables.net/1.12.1/css/dataTables.bootstrap4.min.css">
<script>
$(document).ready(function () {
$('#example').DataTable();
});
</script>
</head>
<body>
<div id="" class="container">
<!-- <button type="button" onclick="run()"> Click Me </button> -->
<h1 class="text-center">Table of Data</h1>
<!--id="example" -->
<table id="example" class="table ">
<tr>
<th>NO</th>
<th>API</th>
<th>Description</th>
</tr>
</table>
</div>
<script>
const table = document.getElementById("example")
function run() {
var xhr = new XMLHttpRequest();
var url = 'https://api.publicapis.org/entries';
xhr.open("GET", url, true);
xhr.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
// getting res and to convert in json
let res = this.responseText;
let data = JSON.parse(res);
// console.log(data);
//traverse data
let NO =[]
let API = []
let Description = []
for (let i = 0; i < 100; i++) {
NO.push([i]);
API.push(data["entries"][i]["API"])
Description.push(data["entries"][i]["Description"])
}
// to create a table
for (let i = 0; i < 100; i++) {
let row = table.insertRow(i + 1);
//add cells
let cell0 = row.insertCell(0);
let cell1 = row.insertCell(1);
let cell2 = row.insertCell(2);
// to insert the data
cell0.innerHTML = NO [i]
cell1.innerHTML = API[i];
cell2.innerHTML = Description[i];
}
}
}
xhr.send();
}
run()
</script>
</body>
</html>
shall i need to put some specific links are the above things is enough? the output shows a normal table.. i have also called the table's id in script tag also.. is anything need to be done

My array (myLeads) elements are not rendered in HTML list but they are showing correctly in console. I want to print myLeads[ ] elements in HTML list

let myLeads = [];
const inputEl = document.getElementById("input-el");
const inputBtn = document.getElementById("input-btn");
const ulEl = document.getElementById("ul-el");
inputBtn.addEventListener("click", function(){
myLeads.push(inputEl.value);
console.log(myLeads)
})
let arr = [2, 3, "fadf"]
/*arr[] elements are rendered correctly in HTML list. But myLeads[] elements are not rendered in HTML list, as they are printed correctly in console.*/
for(let i = 0; i < myLeads.length; i++){
ulEl.innerHTML += "<li>" + myLeads[i] + "</li>"
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=\, initial-scale=1.0">
<title>save leads</title>
<link rel="stylesheet" href="/index.css">
</head>
<body>
<input type="text" id="input-el">
<button id="input-btn">Save tabs</button>
<ul id="ul-el"></ul>
<script src="/index.js"></script>
</body>
</html>
Put the loop in a function and call it. Also make sure to reset the ul to be empty
let myLeads = [];
const inputEl = document.getElementById("input-el");
const inputBtn = document.getElementById("input-btn");
const ulEl = document.getElementById("ul-el");
inputBtn.addEventListener("click", function(){
myLeads.push(inputEl.value);
updateList();
})
let arr = [2, 3, "fadf"]
/*arr[] elements are rendered correctly in HTML list. But myLeads[] elements are not rendered in HTML list, as they are printed correctly in console.*/
function updateList(){
ulEl.innerHTML = "";
for(let i = 0; i < myLeads.length; i++){
ulEl.innerHTML += "<li>" + myLeads[i] + "</li>"
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=\, initial-scale=1.0">
<title>save leads</title>
<link rel="stylesheet" href="/index.css">
</head>
<body>
<input type="text" id="input-el">
<button id="input-btn">Save tabs</button>
<ul id="ul-el"></ul>
<script src="/index.js"></script>
</body>
</html>
You are not updating the HTML element anywhere when the click event is being fired. That means your list is only populated by the initial elements of myLeads when the page is refreshed and then never again.
Move the cycle for generating li elements into a function, for example
function updateList(arr){
ulEl.innerHTML = "";
for(let i = 0; i < arr.length; i++){
ulEl.innerHTML += "<li>" + myLeads[i] + "</li>"
}
}
and then call it inside the event handler
inputBtn.addEventListener("click", function(){
myLeads.push(inputEl.value);
console.log(myLeads)
updateList(myLeads);
})

Decrease input number in javascript

I just started learning javascript. I develop an input box that user enters a number in. so program decrease number to zero.
my problem is here; I enter a number and show same it in output, but show a decreasing number.
my JS code :
function test() {
var MyInput = parseInt(document.getElementById('HoursOfWork').value);
var Exp_MyInput = document.getElementById('output01').innerHTML = "Number: " + MyInput;
for (var i = 1; i < 4; i++) {
document.getElementById('output01').innerHTML = MyInput;
}
}
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<link rel="stylesheet" href="StyleSheet.css" />
<script src="Script.js"></script>
<title>EyeProctect Project</title>
</head>
<body>
<h1>Eye Protect</h1>
<h4>Keep Your Eyes safe</h4>
<input type="text" id="HoursOfWork" placeholder="Enter your hours of work ...." />
<button class="start" onclick=test()>Let's Go!</button>
<p id="output01"></p>
</body>
</html>
What am I do?
If you meant counting down from number provided in input field down to zero using for loop then you can work with this approach:
function test() {
var MyInput = parseInt(document.getElementById('HoursOfWork').value);
var output = document.getElementById('output01');
output.innerHTML = '';
for (var i = MyInput; i > 0; i--) {
output.innerHTML += "Number: " + i + "<br>";
}
}

random numbers between 1 and 50; 50 times

I´m almost got it, but it still not working out like I want
it -- I got s var a = generates an integer between 1 and 50
the integer (result) is output in a textare id("tt4")
but I can't get it done 50 times, I tried to use a for loop // but like I said, I´m
hanging here...
function add() {
var a = Math.floor(Math.random() * 50) + 1;
for (var i = 0; i < 49; i++) {
document.getElementById("tt4").innerHTML = a + ('\n');
}
}
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="style.css" media="screen" />
</head>
<body>
<button onclick="add()">OK</button>
<br><br>
<textarea id="tt4" name="t4"></textarea>
</body>
</html>
I know that the problem is in the for-loop, because 'nothing' hapens with the var i inside the loop // but I can't figure it out
You need to concatenate the innerHTML property in order to update the display. You also need to move your random number generation into your loop. Here is a sample:
function add() {
for (var i = 0; i < 49; i++) {
var a = Math.floor(Math.random() * 50) + 1;
document.getElementById("tt4").innerHTML += a + ('\n');
}
}
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="style.css" media="screen" />
</head>
<body>
<button onclick="add()">OK</button>
<br><br>
<textarea id="tt4" name="t4"></textarea>
</body>
</html>
You will need to use += instead of = when setting the innerHTML of the textarea (which will add more HTML instead of replacing the HTML with the current random number).
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="style.css" media="screen" />
</head>
<body>
<button onclick="add()">OK</button>
<br><br>
<textarea id="tt4" name="t4"></textarea>
<script>
function add() {
for (var i = 0; i < 49; i++) {
var a = Math.floor(Math.random() * 50) + 1;
document.getElementById("tt4").innerHTML += a + ('\n');
}
}
</script>
</body>
</html>
If you place the random() inside the loop, each iteration generates a new number, otherwise you have the same number. Also += add content, intead of =, that assign and replace the content.
for (var i = 0; i < 49; i++) {
var a = Math.floor(Math.random() * 50) + 1;
document.getElementById("tt4").innerHTML += a + ('\n');
}
<textarea id="tt4" name="t4"></textarea>

Javascript Lingo game - String char equal to another string char

Wat i am trying to do is that if checkW string has a letter that is in the checkR than i want this letter to apear as var length = random.length; document.write(Array(length).join("?")); but instead of ? at the letters place it has to show that letter until the whole word is found.
Example: if i type endu and the country that has randomly been choose is Nederland that i want to output this nede???nd because we only found this letters in the string.
<!DOCTYPE html>
<html lang="nl">
<head>
<meta charset="utf-8">
<title>Lingo spel</title>
<meta name="description" content="Lingo spel voor de eu landen en hoofdsteden.">
<meta name="Author" content="Ronald Julian Dewindt">
<link rel="stylesheet" type="text/css" href="css/style.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">
<link rel="stylesheet" type="text/css" href="style.css">
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
</head>
<body>
<h3>Lingo spel - Eu landen en hoofdsteden</h3>
<label>Typ een woord in:</label>
<input type="text" value="" id="woord">
<button type="button" onclick="lingo()">Check</button>
<br><br>
<p><b>Woorden geprobeerd!</b></p>
<p id="try">-----</p>
<script type="text/javascript">
var euLanden = new Array('Nederlands','Duitsland','Zweden');
var random = euLanden[Math.floor(Math.random() * euLanden.length)];
var random = random.toLowerCase();
var woordenG= new Array();
function lingo()
{
var woord = document.getElementById("woord").value;
var woord = woord.toLowerCase();
if(woord == "")
{
alert("U bent vergeten een woord in te typen!");
return;
}
woordenG.push(woord);
document.getElementById("try").innerHTML=woordenG;
var checkW = woord.split('');
var checkR = random.split('');
alert(checkW);
for(i=0; i<checkW.length; i++) //starts at 0++
{
alert(checkW[i]);
/*if(checkW[i] == checkR)
{
alert("Its working");
}*/
}
}
</script>
<p id="hidden"><script>
var length = random.length; document.write(Array(length).join("?"));
</script></p>
</body>
</html>
iterate over all letters in the country name and check if they are present somewhere in the user's "input". if so, append them to the result, if not, append a question mark to the result:
function mask(countryName, textInput)
{
var output = "";
for(var i=0; i < countryName.length; i++)
{
if(textInput.contains(countryName[i]))
{
output += countryName[i];
}
else
{
output += "?";
}
}
return output;
}
Example :
> mask("nederland", "endu")
< "nede???nd"
note : your example in the question is somewhat flawed ; if the word in Lingo is "Nederland", and the letters "ENDU" have been guessed, output should be "nede???nd", rather than "nede?????"

Categories