I have a checkout table from where I obtain the values to later send as an API POST request.
I've built two separate arrays and now I need to combine them, and I'm having trouble to achieve this.
This is my code:
let orderItems = "";
let orderArray = [];
let prodsArray = [];
let datesObj = {};
let modifiersArray = [];
let comboMealsArray = [];
let modifiersObj = {};
let modifierID;
let modifierPrice;
for(var i = 0; i < jQuery(".woocommerce-table__line-item.order_item .wc-item-meta li").length; i++){//get modifier id and price from table
modifierID = jQuery(".hidden-modifier-id").eq(i).text();//modifier id is hidden from frontend but obtainable
modifierPrice = jQuery(".wc-item-meta .amount").eq(i).text();//each modifier price
let removePriceSymbols = modifierPrice.replace("€","");
let formatPrice = removePriceSymbols.replace(",", ".");
if(formatPrice === ""){
formatPrice = 0;
}
let actualModifierPrice = parseFloat(formatPrice);
modifiersObj = {[modifierID]: actualModifierPrice}; //outputs: {2971: 1}
modifiersArray.push(modifiersObj);
}
console.log(modifiersArray); // outputs: [{2971: 1}, {2972: 1.5}, {2972: 1.5}, {2971: 1}, {2972: 1.5}, 2990: 0}]
for(var i = 0; i < jQuery(".woocommerce-table__line-item.order_item").length; i++){//get order values from checkout table per row
let prodsObj = {};
let prodName = jQuery(".woocommerce-table__line-item.order_item > .product-name > a").eq(i).text();//get prodName from table cell
let prodQuant = jQuery(".woocommerce-table__line-item.order_item > .product-name > .product-quantity").eq(i).text();//get prodQuant from table cell
let prodDelivetyId = jQuery(".woocommerce-table__line-item.order_item > .product-name > #delivety_api_id_field").eq(i).text();//get delivety prod api id from table cell
let prodTotal = jQuery(".woocommerce-table__line-item.order_item > .product-total > .amount").eq(i).text();//get prodTotal from table cell
let removeQuantSymbols = prodQuant.replace(/[^0-9\.]+/g,"");
let removePriceSymbols = prodTotal.replace("€","");
let formatPrice = removePriceSymbols.replace(",", ".");
orderItems += prodName + " " + prodQuant + " " + prodTotal + "\r\n";
let actualID = parseInt(orderNumber);
let actualQuant = parseInt(removeQuantSymbols);
let actualApiID = parseInt(prodDelivetyId);
let actualPrice = parseFloat(formatPrice);
let prodTotalUni = actualPrice / actualQuant;
//prodsObj.name = prodName;
//prodsObj.id = actualID;
prodsObj.api_id = actualApiID;
prodsObj.count = actualQuant;
prodsObj.price = prodTotalUni;
prodsObj.modifiers = modifiersArray;
prodsArray.push(prodsObj);
}
orderArray.push(prodsArray);
console.log(orderArray);
This is my table chekcout and this is what my API response looks like:
{"2022-12-21":[{"api_id":2753,"count":1,"price":10.5,"modifiers":[{"2971":1},{"2972":1.5},{"2972":1.5},{"2971":1},{"2972":1.5},{"2990":0}]},{"api_id":2753,"count":1,"price":9.5,"modifiers":[{"2971":1},{"2972":1.5},{"2972":1.5},{"2971":1},{"2972":1.5},{"2990":0}]},{"api_id":2748,"count":1,"price":14.5,"modifiers":[{"2971":1},{"2972":1.5},{"2972":1.5},{"2971":1},{"2972":1.5},{"2990":0}]}]}
And I want it to look like this:
{"2022-12-21":[{"api_id":2753,"count":1,"price":10.5,"modifiers":[{"2971":1},{"2972":1.5}]},{"api_id":2753,"count":1,"price":9.5,"modifiers":[{"2972":1.5}]},{"api_id":2748,"count":1,"price":14.5,"modifiers":[{"2971":1},{"2972":1.5},{"2990":0}]}]}
I'm not quite sure how I would achieve this and I'm even having trouble explaning my problem correctly but hopefully you can understand by looking at my code/examples.
This is my table input structure:
<table class="woocommerce-table woocommerce-table--order-details shop_table order_details">
<thead>
<tr>
<th class="woocommerce-table__product-name product-name">Product</th>
<th class="woocommerce-table__product-table product-total">Total</th>
</tr>
</thead>
<tbody>
<tr class="woocommerce-table__line-item order_item">
<td class="woocommerce-table__product-name product-name">
<a>Fried Chicken</a><span id="delivety_api_id_field">2753</span> <strong class="product-quantity">× 1</strong><ul class="wc-item-meta"><li><strong class="wc-item-meta-label">Side Dishes Options:</strong> <p>Rice<span class="hidden-modifier-id">2971</span> (+<span class="woocommerce-Price-amount amount">1,00 <span class="woocommerce-Price-currencySymbol">€</span></span>)</p></li><li><strong class="wc-item-meta-label">Side Dishes Options:</strong> <p>French Fries<span class="hidden-modifier-id">2972</span> (+<span class="woocommerce-Price-amount amount">1,50 <span class="woocommerce-Price-currencySymbol">€</span></span>)</p></li></ul> </td>
<td class="woocommerce-table__product-total product-total">
<span class="woocommerce-Price-amount amount"><bdi>10,50 <span class="woocommerce-Price-currencySymbol">€</span></bdi></span> </td>
</tr>
<tr class="woocommerce-table__line-item order_item">
<td class="woocommerce-table__product-name product-name">
<a>Fried Chicken</a><span id="delivety_api_id_field">2753</span> <strong class="product-quantity">× 1</strong><ul class="wc-item-meta"><li><strong class="wc-item-meta-label">Side Dishes Options:</strong> <p>French Fries<span class="hidden-modifier-id">2972</span> (+<span class="woocommerce-Price-amount amount">1,50 <span class="woocommerce-Price-currencySymbol">€</span></span>)</p></li></ul> </td>
<td class="woocommerce-table__product-total product-total">
<span class="woocommerce-Price-amount amount"><bdi>9,50 <span class="woocommerce-Price-currencySymbol">€</span></bdi></span> </td>
</tr>
<tr class="woocommerce-table__line-item order_item">
<td class="woocommerce-table__product-name product-name">
<a>Steak</a><span id="delivety_api_id_field">2748</span> <strong class="product-quantity">× 1</strong><ul class="wc-item-meta"><li><strong class="wc-item-meta-label">Side Dishes Options:</strong> <p>Rice<span class="hidden-modifier-id">2971</span> (+<span class="woocommerce-Price-amount amount">1,00 <span class="woocommerce-Price-currencySymbol">€</span></span>)</p></li><li><strong class="wc-item-meta-label">Side Dishes Options:</strong> <p>French Fries<span class="hidden-modifier-id">2972</span> (+<span class="woocommerce-Price-amount amount">1,50 <span class="woocommerce-Price-currencySymbol">€</span></span>)</p></li><li><strong class="wc-item-meta-label">Preparation:</strong> <p>Rare<span class="hidden-modifier-id">2990</span></p></li></ul> </td>
<td class="woocommerce-table__product-total product-total">
<span class="woocommerce-Price-amount amount"><bdi>14,50 <span class="woocommerce-Price-currencySymbol">€</span></bdi></span> </td>
</tr>
</tbody>
<tfoot>
<tr>
<th scope="row">Subtotal:</th>
<td><span class="woocommerce-Price-amount amount">34,50 <span class="woocommerce-Price-currencySymbol">€</span></span></td>
</tr>
<tr>
<th scope="row">Shipping:</th>
<td>Local pickup</td>
</tr>
<tr>
<th scope="row">Payment method:</th>
<td>Multibanco</td>
</tr>
<tr>
<th scope="row">Total:</th>
<td><span class="woocommerce-Price-amount amount">34,50 <span class="woocommerce-Price-currencySymbol">€</span></span></td>
</tr>
</tfoot>
</table>
Edit after all comments
let orderItems = "";
let orderArray = [];
let prodsArray = [];
let datesObj = {};
let comboMealsArray = [];
let modifiersObj = {};
let modifierID;
let modifierPrice;
for(var i = 0; i < jQuery(".woocommerce-table__line-item.order_item").length; i++){//get order values from checkout table per row
let prodsObj = {};
let prodName = jQuery(".woocommerce-table__line-item.order_item > .product-name > a").eq(i).text();//get prodName from table cell
let prodQuant = jQuery(".woocommerce-table__line-item.order_item > .product-name > .product-quantity").eq(i).text();//get prodQuant from table cell
let prodDelivetyId = jQuery(".woocommerce-table__line-item.order_item > .product-name > #delivety_api_id_field").eq(i).text();//get delivety prod api id from table cell
let prodTotal = jQuery(".woocommerce-table__line-item.order_item > .product-total > .amount").eq(i).text();//get prodTotal from table cell
let removeQuantSymbols = prodQuant.replace(/[^0-9\.]+/g,"");
let removePriceSymbols = prodTotal.replace("€","");
let formatPrice = removePriceSymbols.replace(",", ".");
orderItems += prodName + " " + prodQuant + " " + prodTotal + "\r\n";
let modifiersArray = [];
let prodMods = jQuery(".woocommerce-table__line-item.order_item").eq(i).find("li");
for(let prodMod of prodMods) {
modifierID = jQuery(".hidden-modifier-id", prodMod).text();//modifier id is hidden from frontend but obtainable
modifierPrice = jQuery(".amount", prodMod).text();//each modifier price
let removePriceSymbols = modifierPrice.replace("€","");
let formatPrice = removePriceSymbols.replace(",", ".");
if(formatPrice === ""){
formatPrice = 0;
}
let actualModifierPrice = parseFloat(formatPrice);
modifiersObj = {[modifierID]: actualModifierPrice}; //outputs: {2971: 1}
modifiersArray.push(modifiersObj);
}
let actualID = parseInt(orderNumber);
let actualQuant = parseInt(removeQuantSymbols);
let actualApiID = parseInt(prodDelivetyId);
let actualPrice = parseFloat(formatPrice);
let prodTotalUni = actualPrice / actualQuant;
prodsObj.name = prodName;
prodsObj.id = actualID;
prodsObj.api_id = actualApiID;
prodsObj.count = actualQuant;
prodsObj.price = prodTotalUni;
prodsObj.modifiers = modifiersArray;
prodsArray.push(prodsObj);
}
orderArray.push(prodsArray);
console.log(orderArray);
I feel like you should learn a bit more about jQuery, there are things that you can do with it that really fits this situation (like searching for data in a given context). I'll maybe try to refine this even more at some point, but at least this works the way you intended it.
What I've done is create a second loop INSIDE the main loop, that iterates over each li element that represents a modifier, then jQueried the data you needed in that li element context.
Related
in my code, if I run, my data in local storage remove all. how I can delete 1 row where I choice
I confuse how to delete row in table data from local storage
my problem now is, when i click button delete in row table, row choice removed but data in local storage not remove and then when i refresh page, data show again.
function hapus(r){
var i = r.parentNode.parentNode.rowIndex;
document.getElementById("myTable").deleteRow(i);
localStorage.removeItem('dataProduk');
}
Full Code like this
<script type="text/javascript">
$(document).ready(function() {
$('.js-example-basic-single').select2();
$('#getProduks').change(function(e){
let data = $('#getProduks').val();
let datas = data.split('|');
let idProduk = datas[0];
let hargaProduk = datas[1];
let stokProduk = datas[2];
let namaProduk = datas[3];
$('#hargaProduk').val('');
$('#hargaProduk').val(hargaProduk);
})
let dataStore = localStorage.getItem('dataProduk') ? JSON.parse(localStorage.getItem('dataProduk')) : [];
let subAllTotal = 0;
for (var i = 0; i < dataStore.length; i++){
let table = `
<tr>
<td width="10" align="center" scope="row"></td>
<td><button type="submit" onclick="hapus(this)"><i class="fa fa-trash-o"></i></button></td>
<td> ${dataStore[i].namaProduk}</td>
<td> ${dataStore[i].hargaProduk}</td>
<td> ${dataStore[i].disProduk}</td>
<td> ${dataStore[i].jumProduk}</td>
<td> ${(dataStore[i].hargaProduk * dataStore[i].jumProduk) - (dataStore[i].hargaProduk * dataStore[i].jumProduk * dataStore[i].disProduk/100)}</td>
</tr>
`
$('tbody').append(table);
subAllTotal += (dataStore[i].hargaProduk * dataStore[i].jumProduk) - (dataStore[i].hargaProduk * dataStore[i].jumProduk * dataStore[i].disProduk/100)
}
$('#subAllTotal').html(jadiinRupiah(subAllTotal));
$('#tambahProduk').click(function(){
let namaP = $('#getProduks').val().split('|')[3];
let hargaP = $('#hargaProduk').val();
let disP = $('#getDis').val();
let jumP = $('#getJum').val();
let data = {
namaProduk: namaP,
hargaProduk: hargaP,
disProduk: disP,
jumProduk: jumP
}
dataStore.push(data)
localStorage.setItem('dataProduk',JSON.stringify(dataStore))
let subAllTotal = 0;
let table = `
<tr>
<td width="10" align="center" scope="row"></td>
<td><button type="submit" onclick="hapus(this)"><i class="fa fa-trash-o"></i></button></td>
<td> ${data.namaProduk}</td>
<td> ${data.hargaProduk}</td>
<td> ${data.disProduk}</td>
<td> ${data.jumProduk}</td>
<td> ${(data.hargaProduk * data.jumProduk) - (data.hargaProduk * data.jumProduk * data.disProduk/100)}</td>
</tr>
`
$('tbody').append(table);
for (var i = 0; i < dataStore.length; i++){
//subAllTotal += (data.hargaProduk * data.jumProduk) - (data.hargaProduk * data.jumProduk * data.disProduk/100)
subAllTotal += (dataStore[i].hargaProduk * dataStore[i].jumProduk) - (dataStore[i].hargaProduk * dataStore[i].jumProduk * dataStore[i].disProduk/100)
}
$('#subAllTotal').html(jadiinRupiah(subAllTotal));
})
});
$('#hapusProduk').click(function(){
localStorage.clear();
});
function hapus(r){
var i = r.parentNode.parentNode.rowIndex;
document.getElementById("myTable").deleteRow(i);
localStorage.removeItem('dataProduk');
}
function jadiinRupiah(total) {
return new Intl.NumberFormat('en-US', {style: 'currency', currency: 'IDR'}).format(total).split('IDR')[1].trim()
}
You need to get the current array, remove the row and save it again.
function hapus(r){
var i = r.parentNode.parentNode.rowIndex;
document.getElementById("myTable").deleteRow(i);
let data = localStorage.getItem('dataProduk');
data.splice(i,1); //remove data[i]
localStorage.setItem('dataProduk', data);
}
I'm not sure what dataProduk looks like - if it's an array the above solution will work but if it's an object you'll have to use dataProduk.filter
I am trying to change replace an html class based on value.For example if nsndatalength = 0 replace the class name with badge-success
function Awardstable(data) {
var container = document.getElementById('awardsTable');
data.forEach(function(awardsSnap) { // loop over all inventory
var Items = awardsSnap.val();
var nome = Items.Nomenclature;
var NSN = Items.NSN;
var AwardId = Items.Awardid;
var AwrdDate = Items.Awarddate;
var name = Items.Name;
// var quant = Items.Qty;
var cost = Items.Price;
var key = awardsSnap.key;
var NSNref = CatalogueDB.ref("NSNdata/" + NSN).orderByChild("NSN");
if (NSNref) {
// Attach an asynchronous callback to read the data at our posts reference
NSNref.on("value", function(nsnshot) {
if (nsnshot.val()) {
var nsndatalength = Object.keys(nsnshot.val()).length;
} else {
nsndatalength = 0;
}
console.log(nsndatalength)
console.log(nsnshot.val())
var inventoryCard = `
<tr>
<th scope="row">${NSN}</th>
<td>${nome}</td>
<td>${AwardId}</td>
<td>${AwrdDate}</td>
<td class="color-danger">${cost}</td>
<td>
<span class="badge badge-primary" id="sellerqty">${nsndatalength} Sellers</span>
</td>
<td><button type="button" class="btn btn-warning mb-1" id="buymodalbtn" data-toggle="modal" data-target="#buyModal" onclick="buyModal('${NSN}')">
Buy
</button></td>
</tr>
`;
container.innerHTML += inventoryCard;
if (nsndatalength == 0){
var buybtn = document.getElementById('buymodalbtn')
var qtymarker = document.getElementById('sellerqty')
console.log("class",buybtn,qtymarker)
document.getElementById("buymodalbtn").className = document.getElementById("buymodalbtn").className.replace
( /(?:^|\s)btn-warning(?!\S)/g , 'btn-success' )
document.getElementById("sellerqty").className = document.getElementById("sellerqty").className.replace
( /(?:^|\s)badge-primary(?!\S)/g , 'badge-success' )
}
})
} else {
nsndatalength = 0;
console.log("No Awards Available")
}
});
}
The problem is that the code is not working for all inventoryCard. This is the output of the html. The last item 0 sellers and buy button should also change color. What am I doing wrong from the code above?
We can use classList.toggle to toggle a class on/off, with the second parameter we can force it to be on/off.
Here we give the item a unique id:
<span class="badge badge-primary" id="sellerqty-${AwardId}">
then select it with:
document.getElementById(`sellerqty-${AwardId}`)
In your code it would look something like this by giving the item a unique id:
var inventoryCard = `
<tr>
<th scope="row">${NSN}</th>
<td>${nome}</td>
<td>${AwardId}</td>
<td>${AwrdDate}</td>
<td class="color-danger">${cost}</td>
<td>
<span class="badge badge-primary" id="sellerqty-${AwardId}">${nsndatalength} Sellers</span>
</td>
<td>
<button type="button" class="btn btn-warning mb-1" id="buymodalbtn" data-toggle="modal" data-target="#buyModal" onclick="buyModal('${NSN}')">Buy</button>
</td>
</tr>`;
// Add it before we call getElementById
container.innerHTML += inventoryCard;
document.getElementById(`sellerqty-${AwardId}`).classList.toggle('badge-success', nsndatalength == 0)
I’ve made a form where I want the users to be able to add books (title, author, isbn).
<fieldset>
<legend>Bokdata</legend>
<label for="txtBookTitle">Tittel</label>
<input id="txtBookTitle" type="text" value="">
<label for="txtBookAuthor">Forfatter</label>
<input id="txtBookAuthor" type="text" value="">
<label for="txtBookISBN">ISBN</label>
<input id="txtBookISBN" type="text" value="">
<p>
<button onclick="addBookClick()">Legg til</button>
</p>
</fieldset>
The books will appear in this table:
<table border="2">
<thead>
<tr>
<th colspan="3">
Min bokliste
</th>
</tr>
<tr>
<th>Tittel</th>
<th>Forfatter</th>
<th>ISBN</th>
</tr>
</thead>
<tbody id="tblBodyList">
</tbody>
<tfoot id="tblSummary">
</tfoot>
</table>
Adding books by using the input-fields is done by this function:
function addBookClick(){
//Input fra skjemaet
var txtBookTitle = document.getElementById("txtBookTitle").value;
var txtBookAuthor = document.getElementById("txtBookAuthor").value;
var txtBookISBN = document.getElementById("txtBookISBN").value;
// Lag html-tabell
// 0 = tabell 1
var table = document.getElementsByTagName("table")[0];
// Legg til ny rad nederst i tabellen. (0) = øverste rad i tabellen.
var newRow = table.insertRow(table.rows.length);
// Legg til celler i tabellen
var cel1 = newRow.insertCell(0);
var cel2 = newRow.insertCell(1);
var cel3 = newRow.insertCell(2);
// Legg til values i cellene
cel1.innerHTML = txtBookTitle;
cel2.innerHTML = txtBookAuthor;
cel3.innerHTML = txtBookISBN;
}
I’m trying to insert some text into a table without html, but by javascript instead. The easiest would of course be to write the text in the table, but this is a school assignment, and I’m not allowed to do that. Getting help is allowed. I hope I’m close to something, but I could really use some advice. I’ve tried the last two days to get a grip on this:
var txtBookTitle = document.getElementById("txtBookTitle");
var txtBookAuthor = document.getElementById("txtBookAuthor");
var txtBookISBN = document.getElementById("txtBookISBN");
var tblBodyList = document.getElementById("tblBodyList");
var books = [];
var defaultBooks =
"Judo Unleashed,Neil Ohlenkamp,0-07-147534-6\n"+
"Kodokan Judo,Jigoro Kano,0-87011-681-9\n"+
"Olympic Judo,Neil Adams,0-7207-1735-3";
var book = {
title: "txtBookTitle",
author: "txtBookAuthor",
ISBN: "txtBookISBN"
};
function createBook(title, author, ISBN){
var Book = {};
Book.title = title;
Book.author = author;
Book.ISBN = ISBN;
books.push(Book);
return Book
}
var judo = "";
var kodokan = "";
var olympic = "";
function loadDefaultBooks(){
judo = createBook("Judo Unleashed", "Neil Ohlenkamp", "0-07-147534-6");
kodokan = createBook("Kodokan Judo", "Jigoro Kano", "0-87011-681-9");
olympic = createBook("Olympic Judo" , "Neil Adams" , "0-7207-1735-3");
listBooks();
}
In your case you are not calling loadDefaultBooks. Also the function createBook is not making any sense. You can use the same function addBookClick and pass argument.
This line var txtBookTitle = a || document.getElementById("txtBookTitle").value; when a has a value consider that value, other on click of button a will be undefined. In that case consider the value from the input text
function addBookClick(a, b, c) {
//Input fra skjemaet
var txtBookTitle = a || document.getElementById("txtBookTitle").value;
var txtBookAuthor = b || document.getElementById("txtBookAuthor").value;
var txtBookISBN = c || document.getElementById("txtBookISBN").value;
// Lag html-tabell
// 0 = tabell 1
var table = document.getElementsByTagName("table")[0];
// Legg til ny rad nederst i tabellen. (0) = øverste rad i tabellen.
var newRow = table.insertRow(table.rows.length);
// Legg til celler i tabellen
var cel1 = newRow.insertCell(0);
var cel2 = newRow.insertCell(1);
var cel3 = newRow.insertCell(2);
// Legg til values i cellene
cel1.innerHTML = txtBookTitle;
cel2.innerHTML = txtBookAuthor;
cel3.innerHTML = txtBookISBN;
}
function loadDefaultBooks() {
addBookClick("Judo Unleashed", "Neil Ohlenkamp", "0-07-147534-6");
addBookClick("Kodokan Judo", "Jigoro Kano", "0-87011-681-9");
addBookClick("Olympic Judo", "Neil Adams", "0-7207-1735-3");
}
loadDefaultBooks()
<fieldset>
<legend>Bokdata</legend>
<label for="txtBookTitle">Tittel</label>
<input id="txtBookTitle" type="text" value="">
<label for="txtBookAuthor">Forfatter</label>
<input id="txtBookAuthor" type="text" value="">
<label for="txtBookISBN">ISBN</label>
<input id="txtBookISBN" type="text" value="">
<p>
<button onclick="addBookClick()">Legg til</button>
</p>
</fieldset>
<table border="2">
<thead>
<tr>
<th colspan="3">
Min bokliste
</th>
</tr>
<tr>
<th>Tittel</th>
<th>Forfatter</th>
<th>ISBN</th>
</tr>
</thead>
<tbody id="tblBodyList">
</tbody>
<tfoot id="tblSummary">
</tfoot>
</table>
I am creating a dice game. I am trying to make it so the user can re-click a button after the loop as gone through to reset the page to play again. My gut tells me an if statement is involved but after several attempts I cannot figure out how to set it up.
I was able to change the button value to show "play again" after pressed, I just need to get the page to reload after the user re-presses the button "play again." Any help would be appreciated thanks.
<script>
var rolls = new Array();
var maxMoney = 0;
var rollCountMoney = new Array();
var count = 0;
var startingBet = 0;
var betStarter = new Array();
var mostRoll = 0;
function rollDice() {
do {
count++;
var userInput = parseInt(document.getElementById("bet").value);
var wallet = userInput;
var d1 = Math.floor(Math.random() * 6) + 1;
var d2 = Math.floor(Math.random() * 6) + 1;
var diceTotal = d1 + d2;
rolls.push(diceTotal);
rollCountMoney.push(wallet);
if(wallet > maxMoney){
maxMoney = wallet;
mostRoll = count - 1;
}
if(userInput > startingBet){
betStarter.push(userInput);
}
if (diceTotal === 7) {
document.getElementById("bet").value = wallet += 4;
console.log("Round: " + count + " ,you rolled a " + diceTotal + "! You win $4 for a total of: " +wallet);
} else {
document.getElementById("bet").value = wallet -= 1;
console.log("Round: " + count + " ,you rolled a " + diceTotal + "! You lose $1 for a total of: " +wallet);
}
} while (wallet > 0) {}
var displayMsg = count;
var highest = maxMoney;
var highestRoll = mostRoll;
document.getElementById("display").innerHTML = displayMsg;
document.getElementById("starter").innerHTML = betStarter[0];
document.getElementById("highPot").innerHTML = highest;
document.getElementById("rollPot").innerHTML = highestRoll;
var elem = document.getElementById("playAgain");
if (elem.value=="Play Again"){
elem.value = "Play";
}else {elem.value = "Play Again";
}
}
</script>
</head>
<body>
<div class="container-fluid">
<div class="page-head">
<h1 align="center">Lucky Sevens</h1>
</div>
</div>
<div class="container" align="center">
<table class="table-responsive">
<tr>
<th><h3 align="center"><b>Lucky Sevens</b></h3></th>
</tr>
<tr>
<td>
<form>
Starting Bet:
<input id="bet" type="text"/>
</form>
</td>
</tr>
<tr>
<td align="center">
<form>
<input type="button" id="playAgain" onclick="rollDice()" value="Play"></input>
</form>
</td>
</tr>
</table>
<div class="jumbotron" style="width:400px; position: relative; top: 40px">
<table class="dicey" border="1" style="border-color: white">
<caption ALIGN="top">
<h3 align="center" style="color: black"><b><u>Results</u></b></h3>
</caption>
<tr>
<th style= "background-color: grey"><b>Starting Bet</b></th>
<th style= "background-color: grey" id="starter"></th>
</tr>
<tr>
<td>Total rolls before going broke </td>
<td id="display"></td>
</tr>
<tr>
<td>Highest amount won </td>
<td id="highPot"></td>
</tr>
<tr>
<td>Roll count at highest amount won </td>
<td id="rollPot"></td>
</tr>
</table>
</div>
</div>
If I understood your code correctly, you can either reload the page:
function rollDice(){
if (document.getElementById("playAgain").value=="Play Again")
location.reload();
...
or reset it to the initial state:
function rollDice() {
var rolls = new Array();
var maxMoney = 0;
var rollCountMoney = new Array();
var count = 0;
var startingBet = 0;
var betStarter = new Array();
var mostRoll = 0;
document.getElementById("display").innerHTML = "";
document.getElementById("starter").innerHTML = "";
document.getElementById("highPot").innerHTML = "";
document.getElementById("rollPot").innerHTML = "";
...
The simplest way would be to add a second button for play again like
<button id="play-again-button" style="display:none" onclick="location.reload()">play again</button >
Then show it when you need to via
document.getElementById("play-again-button').style.display = "block";
If you want to actually refresh the page. Or tie that button's onclick to a js function that resets things.
This is for a project in progress. I need to create a calculation that will grab the number from the 'total' row in the 'off column' in the table, then minus this from the starting balance that is defined in the input box. The result of this calculation then needs to be displayed in an alert box when the submit button is clicked.
It's a bit beyond me and if anyone could point me in the right direction I would be grateful.
HTML:
<!DOCTYPE html>
<html>
<head>
<h1><em>EXPENSES CALCULATOR</em></h1>
<link rel="stylesheet" type="text/css" href="tt.css"/>
</head>
<body>
<p id="balance">Starting balance (£)<input type="number"></p>
<p>
<input type="button" id="addNewRow" value="Add new row">
<input type="button" onClick="window.print()" value="Print your purchases"/>
</p>
<table id="breakdowntable">
<tr>
<th>Payment type</th>
<th>Off</th>
<th>To come off</th>
<th>Total</th>
</tr>
<tr id="card">
<th>Card Payment</th>
<td>0</td>
<td>0</td>
<td id="cardtotal">0</td>
</tr>
<tr id="cash">
<th>Cash Payment</th>
<td>0</td>
<td>0</td>
<td id="cashtotal">0</td>
</tr>
<tr id="other">
<th>Other Payment</th>
<td>0</td>
<td>0</td>
<td id="othertotal">0</td>
</tr>
<tr id="total">
<th>Total</th>
<td>0</td>
<td>0</td>
<td>0</td>
</tr>
</table>
<table id="purchases"> </table>
<p><input type="Submit" id="submit" onclick='alert(money_to_number())'> </p>
<script type="text/javascript" src="tt.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"> </script>
</body>
</html>
JavaScript:
var doc = document;
function calculateAmount() {
var purchases = doc.getElementById('purchases');
var purchasesRows = purchases.rows;
var typeValue = {'CP' : [0,0], 'CA' : [0,0], 'OP' : [0,0]};
for (var i = 0, purchasesRowsLength = purchasesRows.length, pytType, inputs, isItOffInput, isItOff; i < purchasesRowsLength; ++i) {
pytType = purchasesRows[i].getElementsByTagName('SELECT')[0];
inputs = purchasesRows[i].getElementsByTagName('INPUT');
isItOffInput = inputs[0];
isItOff = inputs[inputs.length - 1].checked ? 0 : 1;
typeValue[pytType.value][isItOff] += isItOffInput.value - 0;
}
var total = [0, 0];
var cardCells = doc.getElementById('card').cells;
cardCells[1].innerHTML = typeValue['CP'][0];
total[0] += typeValue['CP'][0];
cardCells[2].innerHTML = typeValue['CP'][1];
total[1] += typeValue['CP'][1];
cardCells[3].innerHTML = typeValue['CP'][0] + typeValue['CP'][1];
var cashCells = doc.getElementById('cash').cells;
cashCells[1].innerHTML = typeValue['CA'][0];
total[0] += typeValue['CA'][0];
cashCells[2].innerHTML = typeValue['CA'][1];
total[1] += typeValue['CA'][1];
cashCells[3].innerHTML = typeValue['CA'][0] + typeValue['CA'][1];
var otherCells = doc.getElementById('other').cells;
otherCells[1].innerHTML = typeValue['OP'][0];
total[0] += typeValue['OP'][0];
otherCells[2].innerHTML = typeValue['OP'][1];
total[1] += typeValue['OP'][1];
otherCells[3].innerHTML = typeValue['OP'][0] + typeValue['OP'][1];
var totalCells = doc.getElementById('total').cells;
totalCells[1].innerHTML = total[0];
totalCells[2].innerHTML = total[1];
totalCells[3].innerHTML = total[0] + total[1];
}
function addNewRow() {
var purchases = doc.getElementById('purchases');
var row = purchases.insertRow(purchases.rows.length);
var pytTypeCell = row.insertCell(0);
var type = [['CP', 'Paid by Card £'], ['CA', 'Paid with Cash £'], ['OP', 'Other Payment type £']];
var pytType = doc.createElement('SELECT');
for (var i = 0, typeLength = type.length, option; i < typeLength; ++i) {
option = doc.createElement('OPTION');
option.value = type[i][0];
option.innerHTML = type[i][1];
pytType.appendChild(option);
}
pytType.onchange = calculateAmount;
var pytTypeLabel = doc.createElement('LABEL');
pytTypeLabel.innerHTML = 'Type';
pytTypeLabel.appendChild(pytType);
pytTypeCell.appendChild(pytTypeLabel);
var isItOffInput = doc.createElement('INPUT');
isItOffInput.type = 'number';
isItOffInput.onkeyup = calculateAmount;
pytTypeCell.appendChild(isItOffInput);
var descriptInputCell = row.insertCell(1);
var descriptInput = doc.createElement('INPUT');
descriptInput.type = 'number';
var descriptLabel = doc.createElement('LABEL');
descriptLabel.innerHTML = 'Description';
descriptLabel.appendChild(descriptInput);
descriptInputCell.appendChild(descriptLabel);
var dateInputCell = row.insertCell(2);
var dateInput = doc.createElement('INPUT');
dateInput.type = 'date';
var dateLabel = doc.createElement('LABEL');
dateLabel.innerHTML = 'Payment Date';
dateLabel.appendChild(dateInput);
dateInputCell.appendChild(dateLabel);
var isItOffCheckBoxCell = row.insertCell(3);
var isItOffCheckBox = doc.createElement('INPUT');
isItOffCheckBox.type = 'checkbox';
isItOffCheckBox.onclick = calculateAmount;
var isItOffLabel = doc.createElement('LABEL');
isItOffLabel.appendChild(isItOffCheckBox);
isItOffLabel.appendChild(document.createTextNode('Is it Off?'));
isItOffCheckBoxCell.appendChild(isItOffLabel);
}
doc.getElementById('addNewRow').onclick = addNewRow;
window.onload = function() {
addNewRow();
};
Here it is in a jsFiddle: http://jsfiddle.net/jfBAJ/
You need to give ids to the elements you want to find later. I gave your starting balance input the id "starting_balance" and I gave your grand total TD the id of "grand_total" then wrote the following onSubmit:
document.getElementById("submit").onclick = onSubmit
function onSubmit(){
var starting = document.getElementById("starting_balance").value;
var grandTotal = document.getElementById("grand_total").innerHTML;
var finalBalance =parseFloat(grandTotal||0) + parseFloat(starting||0);
alert(finalBalance);
}
This alerts the new total + the starting balance.