I have arrays of strings with names and surnames. I created username which consist of random name and random surname and I want to display different username in every generated tile. I tried to splite names and surnames and than add it do array and get random array index but it didn't work. Better solution would be to use my "username". Biggest problem is that I can't modify my getData() function - it always assign the same username to each tile.
function createGrid(x, y) {
for (var cols = 0; cols < x; cols++) {
for (var rows = 0; rows < y; rows++) {
console.log(namesArr)
console.log(x*y)
numberOfTiles = x*y;
var randonIndex = Math.floor(Math.random() * numberOfTiles);
// $(".usernameSpace").html(namesArr[randomIndex]);
//Doesn't work here
$('#container').append("<div class='grid'><div class = 'usernameSpace'></div></div>");
};
};
$('.grid').width(800 / x);
$('.grid').height(800 / x);
};
function refreshGrid() {
var x = $("#colsNumber")[0].value;
var y = $("#rowsNumber")[0].value;
$('.grid').remove();
createGrid(x, y);
};
function getData(count) {
var names = ["Michal ", "Jan ", "Katarzyna ", "Andrzej ", "Jozef ", "Bartek ", "Mikolaj ", "Tomasz ", "Julian ", "Brajan ", "Dzesika "];
var surnames = ["Noga ", "Kowalski ", "Nowak ", "Pazura ", "Duda ", "Komorowski ", "Tomczyk ", "Jozefowicz ", "Lechicki ", "Goldberg "];
result = [];
for (var i = 0; i < count; i++) {
var randomNameIndex = Math.floor(Math.random() * names.length);
var randomSurnameIndex = Math.floor(Math.random() * surnames.length);
var name = names[randomNameIndex];
var surname = surnames[randomSurnameIndex];
result.push({
name: name,
surname: surname
});
}
return result
}
function textDisplay() {
var numberOfTiles = 12;
//for (i = 0; i <= numberOfTiles; i++) {
var data = getData(12);
//var username = "";
////////////////////////////////////////////////////////////////////
username = "";
$.each(data, function (i, { name, surname }) {
username += ` ${name} ${surname}`;
});
////////////////////////////////////////////////////////////////////
// }
namesToDisplay = "";
surnamesToDisplay = "";
$.each(data, function (i, { name }) {
namesToDisplay += `${name}`;
});
$.each(data, function (i, { surname }) {
surnamesToDisplay += `${surname}`;
});
console.log(username)
console.log(namesToDisplay)
console.log(surnamesToDisplay)
//$(".usernameSpace").html(username);
namesArr = namesToDisplay.split(" ");
console.log(namesArr)
$(".usernameSpace").html(namesArr[2]);
}
function AssignUsername(Class, content) {
var container = document.getElementsByClassName(Class);
$(container).html(content);
}
$(document).ready(function () {
$(".startBtn").click(function () {
refreshGrid();
textDisplay();
});
});
#container {
position: relative;
margin:auto;
height:800px;
width:800px;
}
.grid{
outline:5px solid white;
margin:0;
padding:0;
border:none;
background-color: #212121;
display:inline-block;
color: white;
}
.input{
width: 15%;
background-color: #757575;
font-size: 18px;
border: 3px;
height: 4%;
border-radius: 5px;
color: white;
}
html {
font-family: 'Arial';
}
.startBtn{
background-color: #4b4b4b;
border-radius: 10px;
color: white;
}
#textDisplay{
height:800px;
width:800px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<head>
<link rel=stylesheet type="text/css" href="MetroUI 03'2018 basic.css">
<script src="jquery.js"></script>
<script src="MetroUI 03'2018 basic.js"></script>
</head>
<body onload="textDisplay()">
<p>
Give me width of grid:
</p>
<div>
<input class='input' id='colsNumber' type='number'>
</div>
<p>
Give me height of grid:
</p>
<div>
<input class='input' id='rowsNumber' type='number'>
</div>
<button class="startBtn">START!</button>
<div class='nameDisplay'></div>
<div class="Container"></div>
<div id = "container"></div>
</body>
</html>
In your code when you do:
$(".usernameSpace").html(namesArr[2]);
You are assigning all titles with that class to the same HTML values. Instead iterate through your titles and assign it a value based on your data variable:
$(".usernameSpace").each(function(idx){
$(this).html(data[idx].surname);
});
Although I'd recommend storing the names directly in the data attribute of the .usernameSpace elements as you create them. Then you could just use $(this).data("surname") when you iterate through your elements. That way will be more safer as well in the event that data and the number of .usernameSpace elements differs, along with that it will make the code simpler.
Here is a fiddle example of what I described above
function createGrid(x, y) {
for (var cols = 0; cols < x; cols++) {
for (var rows = 0; rows < y; rows++) {
console.log(namesArr)
console.log(x*y)
numberOfTiles = x*y;
var randonIndex = Math.floor(Math.random() * numberOfTiles);
// $(".usernameSpace").html(namesArr[randomIndex]);
//Doesn't work here
$('#container').append("<div class='grid'><div class = 'usernameSpace'></div></div>");
};
};
$('.grid').width(800 / x);
$('.grid').height(800 / x);
};
function refreshGrid() {
var x = $("#colsNumber")[0].value;
var y = $("#rowsNumber")[0].value;
$('.grid').remove();
createGrid(x, y);
};
function getData(count) {
var names = ["Michal ", "Jan ", "Katarzyna ", "Andrzej ", "Jozef ", "Bartek ", "Mikolaj ", "Tomasz ", "Julian ", "Brajan ", "Dzesika "];
var surnames = ["Noga ", "Kowalski ", "Nowak ", "Pazura ", "Duda ", "Komorowski ", "Tomczyk ", "Jozefowicz ", "Lechicki ", "Goldberg "];
result = [];
for (var i = 0; i < count; i++) {
var randomNameIndex = Math.floor(Math.random() * names.length);
var randomSurnameIndex = Math.floor(Math.random() * surnames.length);
var name = names[randomNameIndex];
var surname = surnames[randomSurnameIndex];
result.push({
name: name,
surname: surname
});
}
return result
}
function textDisplay() {
var numberOfTiles = 12;
//for (i = 0; i <= numberOfTiles; i++) {
var data = getData(12);
//var username = "";
////////////////////////////////////////////////////////////////////
username = [];
$.each(data, function (i, { name, surname }) {
username.push(` ${name} ${surname}`);
});
////////////////////////////////////////////////////////////////////
// }
namesToDisplay = "";
surnamesToDisplay = "";
$.each(data, function (i, { name }) {
namesToDisplay += `${name}`;
});
$.each(data, function (i, { surname }) {
surnamesToDisplay += `${surname}`;
});
console.log(username)
console.log(namesToDisplay)
console.log(surnamesToDisplay)
//$(".usernameSpace").html(username);
namesArr = namesToDisplay.split(" ");
console.log(namesArr)
$(".usernameSpace").each(function(idx){
$(this).html(username[idx]);
})
}
function AssignUsername(Class, content) {
var container = document.getElementsByClassName(Class);
$(container).html(content);
}
$(document).ready(function () {
$(".startBtn").click(function () {
refreshGrid();
textDisplay();
});
});
#container {
position: relative;
margin:auto;
height:800px;
width:800px;
}
.grid{
outline:5px solid white;
margin:0;
padding:0;
border:none;
background-color: #212121;
display:inline-block;
color: white;
}
.input{
width: 15%;
background-color: #757575;
font-size: 18px;
border: 3px;
height: 4%;
border-radius: 5px;
color: white;
}
html {
font-family: 'Arial';
}
.startBtn{
background-color: #4b4b4b;
border-radius: 10px;
color: white;
}
#textDisplay{
height:800px;
width:800px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<head>
<link rel=stylesheet type="text/css" href="MetroUI 03'2018 basic.css">
<script src="jquery.js"></script>
<script src="MetroUI 03'2018 basic.js"></script>
</head>
<body onload="textDisplay()">
<p>
Give me width of grid:
</p>
<div>
<input class='input' id='colsNumber' type='number'>
</div>
<p>
Give me height of grid:
</p>
<div>
<input class='input' id='rowsNumber' type='number'>
</div>
<button class="startBtn">START!</button>
<div class='nameDisplay'></div>
<div class="Container"></div>
<div id = "container"></div>
</body>
</html>
Related
I recently started a project o add items to tables in a restaurant and save the value.
I started with one Item list and it worked perfectly fine but as soon as I added a second list and tried subtracting/adding items via buttons the amount of items would go down/up but the sum would stay the same.
The Sum still updates when adding new items though.
If added the code below you can execute it like that and test yourself.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Prototyp</title>
<style>
.table{
text-align: center;
line-height: 9vh;
height: 10vh;
}
.tablei{
background-color: #e58e26;
font-size: 44pt;
}
.table-down{
margin-top: 90vh;
}
.left, .right{
width: 45vw;
height: 100vh;
border: solid 1pt black;
display: table-cell;
font-size: 20pt;
}
.wrapperBottom{
display: none;
}
.btn{
background-color: #e58e26 !important;
}
.btn-right{
font-size: 28pt;
margin-left: 15vh;
color: #e58e26;
}
body{
background-color: #292929;
color: white;
font-size: 16pt;
font-weight: bold;
}
</style>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
</head>
<body onload="init()">
<div class="row" id="up">
<div class="table tablei col s1" onclick="goNext(1)">1</div>
</div>
<div class="row wrapperBottom" id="bottom">
<div class="col s5" id="sum"></div>
<div class="col s2">
<a class="waves-effect waves-light btn table-down" onclick="goBack()">back to table</a>
</div>
<div class="wrapperacordion">
<button class="accordion accordionheadings">Softdrinks</button>
<div class="col s5 accordionbabahaft" id="Softdrinks"></div>
<button class="accordion accordionheadings">Juice</button>
<div class="col s5 accordionbabahaft" id="Juice"></div>
</div>
</div>
<script>
let tables;
let currentTable;
let products;
softdrinks = [
{name:"Water", price:2.40},
{name:"Soda", price:2.70},
]
juice = [
{name:"OrangeJuice", price:2.40},
{name:"AppleJuice", price:3.90},
{name:"BananaJuice", price:2.40}
]
function init() {
tables = [];
products = [];
products['Softdrinks'] = softdrinks;
products['Juice'] = juice;
}
function goNext(tablenumber){
currentTable = tablenumber;
if(!tables[tablenumber]){
tables[tablenumber] = {products: [], sum: 0};
}
document.getElementById("bottom").style.display = 'block';
document.getElementById("up").style.display = 'none';
document.getElementById("Softdrinks").innerHTML = "";
document.getElementById("Juice").innerHTML = "";
for (let list in products) {
for (let prod of products[list]){
let button = document.createElement("a");
button.setAttribute('class', 'button accordionitems');
button.onclick = () =>{
let entry = null;
for (let pos of tables[tablenumber].products) {
if(pos.name === prod.name){
entry = pos;
}
}
if(!entry){
entry = {name:prod.name, amount: 0, price: 0}
tables[tablenumber].products.push(entry)
}
entry.amount++;
entry.price+= prod.price;
updateSum();
}
button.innerText = prod.name + " " + prod.price + "€";
document.getElementById(list).append(button)
updateSum();
}
}
}
function findPrice(name) {
let price = 0;
for(let prod of products){
if(prod.name === name){
price = prod.price;
break;
}
}
return price;
}
function updateSum(){
document.getElementById("sum").innerHTML = "";
let sum = 0;
let hr = document.createElement("hr");
let sumDiv = document.createElement("div");
let deleteButton = document.createElement("a");
deleteButton.setAttribute('class', 'waves-effect waves-light btn');
for (let prod of tables[currentTable].products) {
let div = document.createElement("div");
let label = document.createElement("span");
label.innerHTML = prod.amount + "x " + prod.name +": "+ prod.price.toFixed(2) +"€ ";
sum += prod.price;
let divPlusMinus = document.createElement("aside");
div.appendChild(divPlusMinus);
divPlusMinus.setAttribute('class', 'gorightpls');
let plus = document.createElement("a");
plus.setAttribute('class', 'btn-plus');
plus.innerHTML ="+ ";
plus.addEventListener("click", ()=>{
prod.amount++;
prod.price+= findPrice(prod.name);
updateSum();
});
let minus = document.createElement("a");
minus.setAttribute('class', 'btn-minus');
minus.addEventListener("click", ()=>{
prod.amount--;
prod.price-= findPrice(prod.name);
updateSum();
});
minus.innerHTML ="− ";
div.append(label);
div.append(minus);
divPlusMinus.append(plus);
divPlusMinus.append(minus);
document.getElementById("sum").append(div)
}
tables[currentTable].sum = sum;
sumDiv.innerHTML = "Sum : "+sum.toFixed(2) +" €"
deleteButton.onclick = () =>{
clicked();
}
deleteButton.innerText ="clear table"
document.getElementById("sum").append(hr)
document.getElementById("sum").append(sumDiv)
document.getElementById("sum").append(deleteButton)
}
function goBack(){
document.getElementById("bottom").style.display = 'none';
document.getElementById("up").style.display = 'block';
}
function clicked() {
var r = confirm("Wirklich löschen?");
if(r==true){
tables[currentTable].products = [];
updateSum();
goBack();
} else {
}
}
document.addEventListener('DOMContentLoaded', function() {
var elems = document.querySelectorAll('select');
var instances = M.FormSelect.init(elems);
});
var acc = document.getElementsByClassName("accordion");
var i;
for (i = 0; i < acc.length; i++) {
acc[i].addEventListener("click", function() {
this.classList.toggle("active");
var panel = this.nextElementSibling;
if (panel.style.display === "block") {
panel.style.display = "none";
} else {
panel.style.display = "block";
}
});
}
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
</body>
</html>
Thanks for helping
let tables;
let currentTable;
let products;
softdrinks = [{
name: "Water",
price: 2.40
},
{
name: "Soda",
price: 2.70
},
]
juice = [{
name: "OrangeJuice",
price: 2.40
},
{
name: "AppleJuice",
price: 3.90
},
{
name: "BananaJuice",
price: 2.40
}
]
function init() {
tables = [];
products = [];
products['Softdrinks'] = softdrinks;
products['Juice'] = juice;
}
function goNext(tablenumber) {
currentTable = tablenumber;
if (!tables[tablenumber]) {
tables[tablenumber] = {
products: [],
sum: 0
};
}
document.getElementById("bottom").style.display = 'block';
document.getElementById("up").style.display = 'none';
document.getElementById("Softdrinks").innerHTML = "";
document.getElementById("Juice").innerHTML = "";
for (let list in products) {
for (let prod of products[list]) {
let button = document.createElement("a");
button.setAttribute('class', 'button accordionitems');
button.onclick = () => {
let entry = null;
for (let pos of tables[tablenumber].products) {
if (pos.name === prod.name) {
entry = pos;
}
}
if (!entry) {
entry = {
name: prod.name,
amount: 0,
price: 0
}
tables[tablenumber].products.push(entry)
}
entry.amount++;
entry.price += prod.price;
updateSum();
}
button.innerText = prod.name + " " + prod.price + "€";
document.getElementById(list).append(button)
updateSum();
}
}
}
function findPrice(name) {
let price = 0;
for (let prod of products) {
if (prod.name === name) {
price = prod.price;
break;
}
}
return price;
}
function updateSum() {
document.getElementById("sum").innerHTML = "";
let sum = 0;
let hr = document.createElement("hr");
let sumDiv = document.createElement("div");
let deleteButton = document.createElement("a");
deleteButton.setAttribute('class', 'waves-effect waves-light btn');
for (let prod of tables[currentTable].products) {
let div = document.createElement("div");
let label = document.createElement("span");
label.innerHTML = prod.amount + "x " + prod.name + ": " + prod.price.toFixed(2) + "€ ";
sum += prod.price;
let divPlusMinus = document.createElement("aside");
div.appendChild(divPlusMinus);
divPlusMinus.setAttribute('class', 'gorightpls');
let plus = document.createElement("a");
plus.setAttribute('class', 'btn-plus');
plus.innerHTML = "+ ";
plus.addEventListener("click", () => {
prod.amount++;
prod.price += findPrice(prod.name);
updateSum();
});
let minus = document.createElement("a");
minus.setAttribute('class', 'btn-minus');
minus.addEventListener("click", () => {
prod.amount--;
prod.price -= findPrice(prod.name);
updateSum();
});
minus.innerHTML = "− ";
div.append(label);
div.append(minus);
divPlusMinus.append(plus);
divPlusMinus.append(minus);
document.getElementById("sum").append(div)
}
tables[currentTable].sum = sum;
sumDiv.innerHTML = "Sum : " + sum.toFixed(2) + " €"
deleteButton.onclick = () => {
clicked();
}
deleteButton.innerText = "clear table"
document.getElementById("sum").append(hr)
document.getElementById("sum").append(sumDiv)
document.getElementById("sum").append(deleteButton)
}
function goBack() {
document.getElementById("bottom").style.display = 'none';
document.getElementById("up").style.display = 'block';
}
function clicked() {
var r = confirm("Wirklich löschen?");
if (r == true) {
tables[currentTable].products = [];
updateSum();
goBack();
} else {}
}
document.addEventListener('DOMContentLoaded', function() {
var elems = document.querySelectorAll('select');
var instances = M.FormSelect.init(elems);
});
var acc = document.getElementsByClassName("accordion");
var i;
for (i = 0; i < acc.length; i++) {
acc[i].addEventListener("click", function() {
this.classList.toggle("active");
var panel = this.nextElementSibling;
if (panel.style.display === "block") {
panel.style.display = "none";
} else {
panel.style.display = "block";
}
});
}
.table {
text-align: center;
line-height: 9vh;
height: 10vh;
}
.tablei {
background-color: #e58e26;
font-size: 44pt;
}
.table-down {
margin-top: 90vh;
}
.left,
.right {
width: 45vw;
height: 100vh;
border: solid 1pt black;
display: table-cell;
font-size: 20pt;
}
.wrapperBottom {
display: none;
}
.btn {
background-color: #e58e26 !important;
}
.btn-right {
font-size: 28pt;
margin-left: 15vh;
color: #e58e26;
}
body {
background-color: #292929;
color: white;
font-size: 16pt;
font-weight: bold;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Prototyp</title>
<link rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
</head>
<body onload="init()">
<div class="row" id="up">
<div class="table tablei col s1" onclick="goNext(1)">1</div>
</div>
<div class="row wrapperBottom" id="bottom">
<div class="col s5" id="sum"></div>
<div class="col s2">
<a class="waves-effect waves-light btn table-down" onclick="goBack()">back to table</a>
</div>
<div class="wrapperacordion">
<button class="accordion accordionheadings">Softdrinks</button>
<div class="col s5 accordionbabahaft" id="Softdrinks"></div>
<button class="accordion accordionheadings">Juice</button>
<div class="col s5 accordionbabahaft" id="Juice"></div>
</div>
</div>
<script>
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
</body>
</html>
After adding categories, your 'products' array now has 2 named properties:
[Softdrinks: Array(2), Juice: Array(3)]
so when you are searching for price in findPrice(), you dont get products list in the first loop. You may:
function findPrice(name) {
let price = 0;
for(let category in products){
for(let prod of products[category]){
if(prod.name === name){
price = prod.price;
break;
}
}
}
return price;
}
Change iteration of products in findPrice().
products having first level of object then inside it list of values. You need two forloop to access this details.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Prototyp</title>
<style>
.table{
text-align: center;
line-height: 9vh;
height: 10vh;
}
.tablei{
background-color: #e58e26;
font-size: 44pt;
}
.table-down{
margin-top: 90vh;
}
.left, .right{
width: 45vw;
height: 100vh;
border: solid 1pt black;
display: table-cell;
font-size: 20pt;
}
.wrapperBottom{
display: none;
}
.btn{
background-color: #e58e26 !important;
}
.btn-right{
font-size: 28pt;
margin-left: 15vh;
color: #e58e26;
}
body{
background-color: #292929;
color: white;
font-size: 16pt;
font-weight: bold;
}
</style>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
</head>
<body onload="init()">
<div class="row" id="up">
<div class="table tablei col s1" onclick="goNext(1)">1</div>
</div>
<div class="row wrapperBottom" id="bottom">
<div class="col s5" id="sum"></div>
<div class="col s2">
<a class="waves-effect waves-light btn table-down" onclick="goBack()">back to table</a>
</div>
<div class="wrapperacordion">
<button class="accordion accordionheadings">Softdrinks</button>
<div class="col s5 accordionbabahaft" id="Softdrinks"></div>
<button class="accordion accordionheadings">Juice</button>
<div class="col s5 accordionbabahaft" id="Juice"></div>
</div>
</div>
<script>
let tables;
let currentTable;
let products;
softdrinks = [
{name:"Water", price:2.40},
{name:"Soda", price:2.70},
]
juice = [
{name:"OrangeJuice", price:2.40},
{name:"AppleJuice", price:3.90},
{name:"BananaJuice", price:2.40}
]
function init() {
tables = [];
products = [];
products['Softdrinks'] = softdrinks;
products['Juice'] = juice;
}
function goNext(tablenumber){
currentTable = tablenumber;
if(!tables[tablenumber]){
tables[tablenumber] = {products: [], sum: 0};
}
document.getElementById("bottom").style.display = 'block';
document.getElementById("up").style.display = 'none';
document.getElementById("Softdrinks").innerHTML = "";
document.getElementById("Juice").innerHTML = "";
for (let list in products) {
for (let prod of products[list]){
let button = document.createElement("a");
button.setAttribute('class', 'button accordionitems');
button.onclick = () =>{
let entry = null;
for (let pos of tables[tablenumber].products) {
if(pos.name === prod.name){
entry = pos;
}
}
if(!entry){
entry = {name:prod.name, amount: 0, price: 0}
tables[tablenumber].products.push(entry)
}
entry.amount++;
entry.price+= prod.price;
updateSum();
}
button.innerText = prod.name + " " + prod.price + "€";
document.getElementById(list).append(button)
updateSum();
}
}
}
function findPrice(name) {
let price = 0;
//console.log(products);
//console.log(name);
for (let prod of Object.values(products)) {
//for(let prod of products){
for(var i =0;i<prod.length; i ++){
if(prod[i].name === name){
price = prod[i].price;
break;
}
}
}
return price;
}
function updateSum(){
document.getElementById("sum").innerHTML = "";
let sum = 0;
let hr = document.createElement("hr");
let sumDiv = document.createElement("div");
let deleteButton = document.createElement("a");
deleteButton.setAttribute('class', 'waves-effect waves-light btn');
for (let prod of tables[currentTable].products) {
let div = document.createElement("div");
let label = document.createElement("span");
label.innerHTML = prod.amount + "x " + prod.name +": "+ prod.price.toFixed(2) +"€ ";
sum += prod.price;
let divPlusMinus = document.createElement("aside");
div.appendChild(divPlusMinus);
divPlusMinus.setAttribute('class', 'gorightpls');
let plus = document.createElement("a");
plus.setAttribute('class', 'btn-plus');
plus.innerHTML ="+ ";
plus.addEventListener("click", ()=>{
prod.amount++;
prod.price+= findPrice(prod.name);
updateSum();
});
let minus = document.createElement("a");
minus.setAttribute('class', 'btn-minus');
minus.addEventListener("click", () => {
prod.amount--;
prod.price-= findPrice(prod.name);
updateSum();
});
minus.innerHTML ="− ";
div.append(label);
div.append(minus);
divPlusMinus.append(plus);
divPlusMinus.append(minus);
document.getElementById("sum").append(div)
}
tables[currentTable].sum = sum;
sumDiv.innerHTML = "Sum : "+sum.toFixed(2) +" €"
deleteButton.onclick = () =>{
clicked();
}
deleteButton.innerText ="clear table"
document.getElementById("sum").append(hr)
document.getElementById("sum").append(sumDiv)
document.getElementById("sum").append(deleteButton)
}
function goBack(){
document.getElementById("bottom").style.display = 'none';
document.getElementById("up").style.display = 'block';
}
function clicked() {
var r = confirm("Wirklich löschen?");
if(r==true){
tables[currentTable].products = [];
updateSum();
goBack();
} else {
}
}
document.addEventListener('DOMContentLoaded', function() {
var elems = document.querySelectorAll('select');
var instances = M.FormSelect.init(elems);
});
var acc = document.getElementsByClassName("accordion");
var i;
for (i = 0; i < acc.length; i++) {
acc[i].addEventListener("click", function() {
this.classList.toggle("active");
var panel = this.nextElementSibling;
if (panel.style.display === "block") {
panel.style.display = "none";
} else {
panel.style.display = "block";
}
});
}
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
</body>
</html>
On the snippet below each cell contains the name of a shape that are taken from a given sequence. I'm trying to update the shape name of the selected cell on ng-click="fadeName(card)", however, when clicking it does update all cells with the same shape name.For instance, if you click row1,col1 which is by default square, all other squares will be updated, I only want to update the selected one. How can I update only the selected cell value ?
// constant variables
var constants = new (function() {
var rows = 10;
var columns = 10;
this.getRows = function() { return rows; };
this.getColumns = function() { return columns; };
})();
// Global Variables
var shapeSequence =
[
{id: '1', name:'square'},
{id: '2', name:'triangle'},
{id: '3', name:'circle'},
{id: '4', name:'oval'},
{id: '5', name:'pentagon'},
{id: '6', name:'hexagon'},
{id: '7', name:'decagon'},
]
// this function creates deck of cards that returns an object of cards
function createDeck() {
var rows = constants.getRows();
var cols = constants.getColumns();
var key = createColors();
var deck = {};
deck.rows = [];
// create each row
for(var i = 0; i < rows; i++) {
var row = {};
row.cards = [];
// creat each card in the row
for (var j = 0; j < cols; j++) {
var card = {};
card.item = key.shift();
row.cards.push(card);
}
deck.rows.push(row);
}
return deck;
}
function createColors() {
var coloredCards = [];
var rows = constants.getRows();
var cols = constants.getColumns();
var cells = rows * cols;
for (var n = 0; n < cells; n++) {
var thisCard = shapeSequence[n % shapeSequence.length];
coloredCards.splice(n, 0, thisCard);
}
return coloredCards;
}
var app = angular.module('cards', ['ngAnimate']);
app.controller("CardController", function($scope) {
$scope.deck = createDeck();
$scope.fadeName = function(card) {
card.item.name = 'black';
}
});
.card_container {
position: relative;
width: 50px;
height: 50px;
text-align: center;
vertical-align: middle;
line-height: 50px;
z-index: 1;
font-size: 1em;
border:solid 1px;
border-color:black;
}
.card_container {
-moz-perspective: 1000;
-webkit-perspective: 1000;
perspective: 1000;
}
.card {
width: 100%;
height: 100%;
cursor: pointer;
}
table {
margin: 0px auto;
}
.cntr {
margin: 15px auto;
}
<html ng-app="cards">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="https://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.min.js" type="text/javascript"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular-animate.min.js" type="text/javascript"></script>
</head>
<body>
<div class="cntr" ng-controller="CardController">
<table >
<tr ng-repeat="row in deck.rows">
<td ng-repeat="card in row.cards">
<div class="card_container " >
<div class="card " ng-click="fadeName(card)" ng-mouseenter="hover = true" ng-mouseleave="hover = false" >
<p ng-if="hover"> {{card.item.name}} </p>
</div>
</div>
</td>
</tr>
</table>
</div>
</html>
While pushing to row
do
card = JSON.parse(JSON.stringify(card));
row.cards.push(card);
You added reference from shapeSequence into your cells where you updated one cells data that will reflect everywhere where you used the same reference. So I only created clone while creating colors in 'createColors()'. clone() is also added.
// constant variables
var constants = new (function() {
var rows = 10;
var columns = 10;
this.getRows = function() { return rows; };
this.getColumns = function() { return columns; };
})();
function clone(obj) {
if (null == obj || "object" != typeof obj) return obj;
var copy = obj.constructor();
for (var attr in obj) {
if (obj.hasOwnProperty(attr)) copy[attr] = obj[attr];
}
return copy;
}
// Global Variables
var shapeSequence =
[
{id: '1', name:'square'},
{id: '2', name:'triangle'},
{id: '3', name:'circle'},
{id: '4', name:'oval'},
{id: '5', name:'pentagon'},
{id: '6', name:'hexagon'},
{id: '7', name:'decagon'},
]
// this function creates deck of cards that returns an object of cards
function createDeck() {
var rows = constants.getRows();
var cols = constants.getColumns();
var key = createColors();
var deck = {};
deck.rows = [];
// create each row
for(var i = 0; i < rows; i++) {
var row = {};
row.cards = [];
// creat each card in the row
for (var j = 0; j < cols; j++) {
var card = {};
card.item = key.shift();
row.cards.push(card);
}
deck.rows.push(row);
}
return deck;
}
function createColors() {
var coloredCards = [];
var rows = constants.getRows();
var cols = constants.getColumns();
var cells = rows * cols;
for (var n = 0; n < cells; n++) {
var thisCard = shapeSequence[n % shapeSequence.length];
coloredCards.splice(n, 0, clone(thisCard));
}
return coloredCards;
}
var app = angular.module('cards', ['ngAnimate']);
app.controller("CardController", function($scope) {
$scope.deck = createDeck();
$scope.fadeName = function(card) {
card.item.name = 'black';
}
});
.card_container {
position: relative;
width: 50px;
height: 50px;
text-align: center;
vertical-align: middle;
line-height: 50px;
z-index: 1;
font-size: 1em;
border:solid 1px;
border-color:black;
}
.card_container {
-moz-perspective: 1000;
-webkit-perspective: 1000;
perspective: 1000;
}
.card {
width: 100%;
height: 100%;
cursor: pointer;
}
table {
margin: 0px auto;
}
.cntr {
margin: 15px auto;
}
<html ng-app="cards">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="https://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.min.js" type="text/javascript"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular-animate.min.js" type="text/javascript"></script>
</head>
<body>
<div class="cntr" ng-controller="CardController">
<table >
<tr ng-repeat="row in deck.rows">
<td ng-repeat="card in row.cards">
<div class="card_container " >
<div class="card " ng-click="fadeName(card)" ng-mouseenter="hover = true" ng-mouseleave="hover = false" >
<p ng-if="hover"> {{card.item.name}} </p>
</div>
</div>
</td>
</tr>
</table>
</div>
</html>
I have recently been working on a project that has resulted in countless hours of frustration. The task is to create a Webpage that calculates a user's total cost depending on the different radio buttons / check boxes they select.
So, assuming all my other functions and constants are correct, is there anything wrong with my function or the calling of my function.
HTML
<input type = "button" value = "Submit" onclick="calculate();">
<table>
<tr><td>Workshop Total:</td> <td><div id="divWorkshopTotal"></div></td></tr>
<tr><td>Lodging Total:</td> <td><div id="divLodgingTotal"></div></td></tr>
<tr><td>Discount Amount:</td> <td><div id="divDiscount"></div></td></tr>
<tr><td>Sales Tax Amount:</td> <td><div id="divSalesTaxAmount"></div></td></tr>
<tr><td>Total Due:</td> <td><div id="divTotal"></div></td></tr>
</table>
JavaScript
function $(elementName){
return document.getElementById(elementName);
}
function calculate(){
clearOutput();
if (checkWorkshopSelected() > 3){
$("divWorkshopError").innerHTML = "* Selected workshops exceeds maximum of " + MAXIMUM_WORKSHOPS_SELECTED;
return;
} else if (checkWorkshopSelected() == 0){
$("divWorkshopError").innerHTML = "* No workshop(s) selected";
return;
}
var workshopCost = calculateWorkshopTotalCost();
var lodgingCost = calculateLodgingCost();
var subtotal = workshopCost + lodgingCost;
var discountRate = calculateDiscountRate();
var discountAmount = subtotal * discountRate;
if ($("chkTaxExempt").checked == false){
var salesTaxAmount = (subtotal - discountAmount) * SALES_TAX_RATE;
}
var totalCost = subtotal - discountAmount + salesTaxAmount;
$("divWorkshopTotal").innerHTML = workshopCost;
$("divLodgingTotal").innerHTML = lodgingCost;
$("divDiscount").innerHTML = discountAmount;
$("divSalesTaxAmount").innerHTML = salesTaxAmount;
$("divTotal").innerHTML = totalCost;
}
Please check out the code and only ask small doubts in comments. Otherwise please make a new question.
var SALES_TAX_RATE = 0.1,
MAXIMUM_WORKSHOPS_SELECTED = 3;
var data = {
productA: 10,
productB: 20,
productC: 25,
};
var prod = document.getElementsByClassName('prod'),
tax = $("tax"),
workshopTotal = $("workshopTotal"),
lodgingTotal = $("lodgingTotal"),
discount = $("discount"),
salesTaxAmount = $("salesTaxAmount"),
total = $("total"),
workshopError = $("workshopError"),
out = document.getElementsByClassName('out');
$("inputButton").addEventListener("click", calculate);
clearOutput();
function $(elementName){
return document.getElementById(elementName);
}
function calculate () {
clearOutput();
if (checkWorkshopSelected() >= MAXIMUM_WORKSHOPS_SELECTED) {
workshopError.innerHTML = "* Selected workshops exceeds maximum of " + MAXIMUM_WORKSHOPS_SELECTED;
return;
} else if (checkWorkshopSelected() == 0) {
workshopError.innerHTML = "* No workshop(s) selected";
return;
}
var workshopCost = calculateWorkshopTotalCost();
var lodgingCost = calculateLodgingCost();
var subtotal = workshopCost + lodgingCost;
var discountRate = calculateDiscountRate();
var discountAmount = subtotal * discountRate;
var salesTax = 0;
if (tax.checked == false){
salesTax = (subtotal - discountAmount) * SALES_TAX_RATE;
}
var totalCost = subtotal - discountAmount + salesTax;
outputPrice(workshopTotal, workshopCost);
outputPrice(lodgingTotal, lodgingCost);
outputPrice(discount, discountAmount);
outputPrice(salesTaxAmount, salesTax);
outputPrice(total, totalCost);
}
function clearOutput () {
for (var i=0; i<out.length; i++) {
var o = out[i];
o.innerHTML = "0,00"
}
workshopError.innerHTML = "";
}
function checkWorkshopSelected () {
var s = 0;
for (var i=0; i<prod.length; i++) {
var p = prod[i];
if (p.checked) s += 1;
}
return s;
}
function calculateLodgingCost () {
return 5;
}
function calculateWorkshopTotalCost () {
var t = 0;
for (var i=0; i<prod.length; i++) {
var p = prod[i];
if (p.checked) t += data[p.id];
}
return t;
}
function calculateDiscountRate () {
return 0.05;
}
function outputPrice (e, p) {
e.innerHTML = p.toFixed(2);
}
p {
line-height: 14px;
width: 200px;
}
#inputButton {
height: 32px;
margin-bottom: 10px;
}
#workshopError {
color: red;
float: right;
margin-bottom: 20px;
}
.prod + label {
font-weight: bold;
}
.out {
display: inline-block;
padding: 4px 12px;
margin: -6px 0;
background: #fff;
border: 1px solid #999;
border-radius: 3px;
font-family: monospace;
float: right;
}
.out:before {
content: "$";
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<p><input type="checkbox" id="productA" class="prod"><label>Workshop A - 10</label></p>
<p><input type="checkbox" id="productB" class="prod"><label>Workshop B - 20</label></p>
<p><input type="checkbox" id="productC" class="prod"><label>Workshop C - 25</label></p>
<p><input type="checkbox" id="tax"><label>Tax 10%</label></p>
<p><input id="inputButton" type="button" value="Submit"><label id="workshopError"></label></p>
<p><label>Workshop Total:</label><span class="out" id="workshopTotal"></span></p>
<p><label>Lodging Total:</label><span class="out" id="lodgingTotal"></span></p>
<p><label>Discount Amount:</label><span class="out" id="discount"></span></p>
<p><label>Sales Tax Amount:</label><span class="out" id="salesTaxAmount"></span></p>
<p><label>Total Due:</label><span class="out" id="total"></span></p>
</body>
</html>
I made a standard deviation calculator but am not sure where I am going wrong in the calculation. I am trying to learn how to manipulate arrays so everything probably takes the long route in what I am doing.
What am I doing wrong?
JavaScript:
myArray = [];
squaredArray = [];
var theTotal;
var average;
var theSquaredTotal;
var meanOfSquaredArray;
var squaredAverage;
var standardDeviation;
$(document).ready(function() {
$('#inTakeButton').on('click', function() {
var inputValue = parseFloat($('#input').val());
if (inputValue === "") {
return;
}
if (isNaN(inputValue)) {
$('#input').val("");
return;
}
myArray.push(inputValue);
$('#input').val("");
});
$('#showArray').on('click', function() {
console.log(myArray);
$('#list').html("");
for (var i = 0; i < myArray.length; i++) {
$('#list').append("<li>" + myArray[i] + "</ul>");
};
$('#doMath').on('click', function() {
theTotal = 0;
for (var i = 0; i < myArray.length; i++) {
theTotal = theTotal + myArray[i];
};
$('#sum').html("");
$('#sum').html("The sum is: " +
theTotal);
average = parseFloat((theTotal /
myArray.length));
$('#average').html("");
$('#average').html(
"The mean value is: " + average
);
for (var i = 0; i < myArray.length; i++) {
squaredArray.push(myArray[i] -
average);
};
console.log(
"the subtracted squared away array is: " +
squaredArray);
for (var i = 0; i < myArray.length; i++) {
squaredArray[i] = Math.pow(
squaredArray[i], 2);
};
console.log(
"the squared away array is: " +
squaredArray);
for (var i = 0; i < squaredArray.length; i++) {
squaredTotal = 0;
squaredTotal = squaredTotal +
squaredArray[i]
};
console.log("The squared sum is: " +
squaredTotal);
//meanOfSquaredArray =
squaredAverage = parseFloat((
squaredTotal / squaredArray
.length));
console.log("The squared average is: " +
squaredAverage);
standardDeviation = Math.sqrt(
squaredAverage);
console.log(
"The standard deviation is: " +
standardDeviation);
});
});
});
CSS:
#wrapper {
width: 80%;
margin: 0 auto;
border: 1px solid #000;
border-radius: 5px 5px 5px 5px;
box-shadow: 5px 5px 10px 3px #000;
padding: 10px;
}
h1 {
text-align: center;
color: orange;
text-shadow: 1px 1px blue;
}
#intake {
text-align: center;
}
HTML:
<div id="wrapper">
<div id="content">
<h1>Standard Deviation</h1>
<div id="intake">
<input id="input" type="text"> <button id="inTakeButton">Push
to Array</button> <button id="showArray">Show Array</button>
<button id="doMath">Do Math</button>
</div>
<div id="middle">
<ul id="list"></ul>
<ul id="sortedList"></ul>
</div>
<div id="output">
<p id="sorted"></p>
<p id="sum"></p>
<p id="average"></p>
</div>
</div>
</div>
Fiddle here.
It´s quite simple mistake, you are doing
for (var i = 0; i < squaredArray.length; i++) {
squaredTotal = 0;
squaredTotal = squaredTotal + squaredArray[i]
};
So in each step, you are resetting squaredTotal to 0, which means when the loop ends, squaredTotal will be equal to the last value of the array. Fix is to put it outside the loop:
squaredTotal = 0;
for (var i = 0; i < squaredArray.length; i++) {
squaredTotal = squaredTotal + squaredArray[i]
};
You have nested two click events:
$('#showArray').on('click', function() {
//
$('#doMath').on('click', function() {
//
});
});
You should move the click event on #doMath out to stand alone so that it can run when you actually click that element.
I am using a for-loop to get the values of a sorted list using .html() but it is only printing the last value in the array. I thought by using myArray.length and myArray[i] in the loop that it would cycle through as expected.
Ideally, I would like this to read:
The sorted values are:
1, 2, 3, 4, 5 etc. . .
What am I doing wrong?
Fiddle here.
HTML:
<div id="wrapper">
<div id="content">
<h1>Let's Do Some Math</h1>
<div id="intake">
<input type="text" id="input"> <button id="inTakeButton">Push to Array</button> <button id="showArray">Show Array</button> <button id="doMath">Do Math</button>
</div>
<div id="middle">
<ul id="list">
</ul>
</div>
<div id="output">
<p id="sorted"></p>
<p id="sum"></p>
<p id="average"></p>
</div>
</div>
</div>
CSS:
#wrapper{
width: 80%;
margin: 0 auto;
border: 1px solid black;
border-radius: 5px 5px 5px 5px;
box-shadow: 5px 5px 10px 3px black;
padding: 10px;
}
h1 {
text-align: center;
color: orange;
text-shadow: 1px 1px blue;
}
#intake {
text-align: center;
}
JavaScript:
myArray = [];
var theTotal;
$(document).ready(function() {
$('#inTakeButton').on('click', function() {
var inputValue = parseFloat($('#input').val());
if (inputValue === "") {
return;
}
if (isNaN(inputValue)) {
$('#input').val("");
return;
}
myArray.push(inputValue);
$('#input').val("");
});
$('#showArray').on('click', function() {
console.log(myArray);
$('#list').html("");
for (var i = 0; i < myArray.length; i++) {
$('#list').append("<li>" + myArray[i] + "</ul>");
};
$('#doMath').on('click', function() {
theTotal = 0;
for (var i = 0; i < myArray.length; i++) {
theTotal = theTotal + myArray[i];
};
$('#sum').html("");
$('#sum').html("The sum is: " + theTotal);
var average = (theTotal/myArray.length);
$('#average').html("");
$('#average').html("The mean value is: " + average);
var sorted = myArray.sort();
$('#sorted').html("");
for (var i = 0; i < myArray.length; i++) {
$('#sorted').html("The sorted values are: <br>" + myArray[i] + ", ");
};
});
});
});
You don't even need to use loop trough the array to do this, just:
$('#sorted').html("The sorted values are: <br>" + myArray.join(", "));
In your loop for the sorted values, you are overriding the entire HTML content each time.
Try something like
for (var i = 0; i < myArray.length; i++) {
$('#sorted').append(myArray[i] + ", ");
};
You can try this. Instead of showing the values using a loop, you can just display the whole array at once. Edited JS code:
myArray = [];
var theTotal;
$(document).ready(function() {
$('#inTakeButton').on('click', function() {
var inputValue = parseFloat($('#input').val());
if (inputValue === "") {
return;
}
if (isNaN(inputValue)) {
$('#input').val("");
return;
}
myArray.push(inputValue);
$('#input').val("");
});
$('#showArray').on('click', function() {
console.log(myArray);
$('#list').html("");
for (var i = 0; i < myArray.length; i++) {
$('#list').append("<li>" + myArray[i] + "</ul>");
};
$('#doMath').on('click', function() {
theTotal = 0;
for (var i = 0; i < myArray.length; i++) {
theTotal = theTotal + myArray[i];
};
$('#sum').html("");
$('#sum').html("The sum is: " + theTotal);
var average = (theTotal/myArray.length);
$('#average').html("");
$('#average').html("The mean value is: " + average);
var sorted = myArray.sort();
$('#sorted').html("The sorted values are: <br>" + myArray )
});
});
});
Check out the fiddle
var sorted = myArray.sort(function (a, b) {
return a - b;
});
use this for sorting