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>
Related
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.
function createPerson() {
var fullname = document.getElementById('inputValueFullname').value;
var age = document.getElementById('inputValueAge').value;
var amka = document.getElementById('inputValueAmka').value;
function person(fullname, age, amka) {
this.fullname = fullname;
this.age = age;
this.amka = amka;
}
var NewPerson = new person(name, age, amka);
console.log(NewPerson);
}
<label>Fullname: <input type="text" id="inputValueFullname"></label>
<label>Age:<input type="text" id="inputValueAge"></label>
<label>Amka:<input type="text" id="inputValueAmka"></label>
<button id="btn" onclick="createPerson();">Add</button>
I want someone to help me with 2 problems
the user gives full name age and amka and I want them all to appear below in a list as in the photo below
I have a code that I tried separately but I do not know how to put them together
i want when someone give age<18 to stop to take more inputs
to use for this for or if and how to do it
function publishToTable() {
const fullname = document.getElementById('fullname').value;
const age = document.getElementById('age').value;
const amka = document.getElementById('amka').value;
const error = document.getElementById('error');
if (fullname && age && amka) {
const tableElement = document.getElementById('table');
const trElement = document.createElement('tr');
const tbodyElement = document.createElement('tbody');
const fullnameEle = document.createElement('td');
const ageEle = document.createElement('td');
const amkaEle = document.createElement('td');
fullnameEle.innerHTML = fullname;
ageEle.innerHTML = age;
amkaEle.innerHTML = amka;
trElement.appendChild(fullnameEle);
trElement.appendChild(ageEle);
trElement.appendChild(amkaEle);
tbodyElement.appendChild(trElement);
tableElement.appendChild(tbodyElement);
}
}
<div class="complete">
<div class="form">
<label>Fullname: <input id="fullname" type="text"></label>
<label>Age: <input id="age" type="text"></label>
<label>AMKA: <input id="amka" type="text"></label>
<span id="error"></span>
<button onclick="publishToTable()">Submit</button>
</div>
<div id="tables">
<table id="table">
<thead>
<tr>
<th>Name/Surname</th>
<th>Age</th>
<th>AMKA</th><br><br><br><br><br>
</tr>
</thead>
</table>
</div>
</div>
I suggest you use an array.
I have made some other recommended changes, such as using an eventListener and an Array.map
const person = (fullname, age, amka) => ({ fullname, age, amka }); // return an object, shorthand for { "fullname": fullname ....
const persons = [];
const error = document.getElementById('error');
const tableElement = document.getElementById('table');
const fullnameField = document.getElementById('fullname')
const ageField = document.getElementById('age')
const amkaField = document.getElementById('amka')
const publishToTable = () => tableElement.innerHTML = persons
.map(({ fullname, age, amka }) => `<tr><td>${fullname}</td><td>${age}</td><td>${amka}</td></tr>`).join("");
document.getElementById("save").addEventListener("click", e => {
let fullname = fullnameField.value;
let age = +ageField.value; // cast to number
let amka = amkaField.value;
if (isNaN(age) || age < 18) {
ageField.focus();
error.innerHTML = "Incorrect age (18 minimum)"
return; // stop
}
error.innerHTML = "";
persons.push(person(fullname, age, amka));
fullnameField.value = ageField.value = amkaField.value = ""; // reset
fullnameField.focus()
publishToTable();
})
<div class="complete">
<div class="form">
<label>Fullname: <input id="fullname" type="text"></label>
<label>Age: <input id="age" type="text"></label>
<label>AMKA: <input id="amka" type="text"></label>
<span id="error"></span>
<button type="button" id="save">Save</button>
</div>
<div id="tables">
<table>
<thead>
<tr>
<th>Name/Surname</th>
<th>Age</th>
<th>AMKA</th><br><br><br><br><br>
</tr>
</thead>
<tbody id="table">
</table>
</table>
</div>
</div>
I'm a beginner to JavaScript. Here I can't figure out why my code isn't reading the values which I input, even-though I can't find out any errors in my code. Any helpful suggestions to edit my code to fix the error?
function gpacalc() {
//define valid grades and their values
var gr = new Array(6);
var cr = new Array(6);
var ingr = new Array(5);
var incr = new Array(5);
// define valid grades and their values
var grcount = 11;
gr[0] = "A+";
cr[0] = 4;
gr[1] = "A";
cr[1] = 4;
gr[2] = "A-";
cr[2] = 3.70;
gr[3] = "B+";
cr[3] = 3.30;
gr[4] = "B";
cr[4] = 3;
gr[5] = "B-";
cr[5] = 2.70;
gr[6] = "C+";
cr[6] = 2.30;
gr[7] = "C";
cr[7] = 2;
gr[8] = "C-";
cr[8] = 1.70;
gr[9] = "D";
cr[9] = 1;
gr[10] = "D-";
cr[10] = 0.70;
// retrieve user input
ingr[0] = document.GPACalcForm.GR1.value;
ingr[1] = document.GPACalcForm.GR2.value;
ingr[2] = document.GPACalcForm.GR3.value;
ingr[3] = document.GPACalcForm.GR4.value;
ingr[4] = document.GPACalcForm.GR5.value;
incr[0] = document.GPACalcForm.CR1.value;
incr[1] = document.GPACalcForm.CR2.value;
incr[2] = document.GPACalcForm.CR3.value;
incr[3] = document.GPACalcForm.CR4.value;
incr[4] = document.GPACalcForm.CR5.value;
// Calculate GPA
var allgr = 0;
var allcr = 0;
var gpa = 0;
for (var x = 0; x < 5; x++) {
if (ingr[x] == "")
break;
alert("Error: You did not enter a numeric credits value for subject. If the subject is worth 0 credits, then enter the number 0 in the field.");
var validgrcheck = 0;
for (var xx = 0; xx < grcount; xx++) {
if (ingr[x] == gr[xx]) {
allgr = allgr + (parseInt(incr[x], 10) * cr[xx]);
allcr = allcr + parseInt(incr[x], 10);
validgrcheck = 1;
break;
}
}
if (validgrcheck == 0) {
alert("Error: Could not recognize the grade entered for subject " + eval(x + 1) + ". Please use standard college grades in the form of A+, A, B+ ... D-");
return 0;
}
}
if (allcr == 0) {
alert("Error:You did not enter any credit values. GPA = N/A");
return 0;
}
gpa = allgr / allcr;
alert("GPA = " + gpa);
return 0;
}
<center>
<form name="GPACalcForm">
<table border="2" bgcolor="#bb8fce" cellpadding="5" cellspacing="2">
<TH> </TH>
<TH>Grade</TH>
<TH>Credits</TH>
<TR>
<TD>IT 201</TD>
<TD><input type="text" size="5" name="GR1" align="top" maxlength="5"></TD>
<TD><input type="text" size="5" name="CR1" align="top" maxlength="5"></TD>
</TR>
<TR>
<TD>IT 202</TD>
<TD><input type="text" size="5" name="GR2" align="top" maxlength="5"></TD>
<TD><input type="text" size="5" name="CR2" align="top" maxlength="5"></TD>
</TR>
<TR>
<TD>IT 203</TD>
<TD><input type="text" size="5" name="GR3" align="top" maxlength="5"></TD>
<TD><input type="text" size="5" name="CR3" align="top" maxlength="5"></TD>
</TR>
<TR>
<TD>IT 204</TD>
<TD><input type="text" size="5" name="GR4" align="top" maxlength="5"></TD>
<TD><input type="text" size="5" name="CR4" align="top" maxlength="5"></TD>
</TR>
<TR>
<TD>IT 205</TD>
<TD><input type="text" size="5" name="GR5" align="top" maxlength="5"></TD>
<TD><input type="text" size="5" name="CR5" align="top" maxlength="5"></TD>
</TR>
<TR>
<TR align="center">
<TD colspan="3">
<input type="button" value="Calculate" name="CalcButton" OnClick="gpacalc()">
</TD>
</TR>
</table>
</form>
<br/>
<p> </p>
</center>
<br/>
I'm a beginner to JavaScript. Here I can't figure out why my code isn't reading the values which I input, even-though I can figure out any errors in my code. Any helpful suggestions to edit my code to fix the error?
function gpacalc()
{
//define valid grades and their values
var gr = new Array(6);
var cr = new Array(6);
var ingr = new Array(5);
var incr = new Array(5);
// define valid grades and their values
var grcount = 11;
gr[0] = "A+";
cr[0] = 4;
gr[1] = "A";
cr[1] = 4;
gr[2] = "A-";
cr[2] = 3.70;
gr[3] = "B+";
cr[3] = 3.30;
gr[4] = "B";
cr[4] = 3;
gr[5] = "B-";
cr[5] = 2.70;
gr[6] = "C+";
cr[6] = 2.30;
gr[7] = "C";
cr[7] = 2;
gr[8] = "C-";
cr[8] = 1.70;
gr[9] = "D";
cr[9] = 1;
gr[10] = "D-";
cr[10] = 0.70;
// retrieve user input
ingr[0] = document.GPACalcForm.GR1.value;
console.log(ingr[0]);
ingr[1] = document.GPACalcForm.GR2.value;
ingr[2] = document.GPACalcForm.GR3.value;
ingr[3] = document.GPACalcForm.GR4.value;
ingr[4] = document.GPACalcForm.GR5.value;
incr[0] = document.GPACalcForm.CR1.value;
incr[1] = document.GPACalcForm.CR2.value;
incr[2] = document.GPACalcForm.CR3.value;
incr[3] = document.GPACalcForm.CR4.value;
incr[4] = document.GPACalcForm.CR5.value;
// Calculate GPA
var allgr = 0;
var allcr = 0;
var gpa = 0;
for (var x = 0; x < 5; x++)
{
if (ingr[x] == "") {
alert("Error: You did not enter a numeric credits value for subject. If the subject is worth 0 credits, then enter the number 0 in the field.");
break;
}
var validgrcheck = 0;
for (var xx = 0; xx < grcount; xx++)
{
if (ingr[x] == gr[xx])
{
allgr = allgr + (parseInt(incr[x],10) * cr[xx]);
allcr = allcr + parseInt(incr[x],10);
validgrcheck = 1;
break;
}
}
console.log(validgrcheck);
if (validgrcheck == 0)
{
alert("Error: Could not recognize the grade entered for subject " + eval(x + 1) + ". Please use standard college grades in the form of A+, A, B+ ... D-");
return 0;
}
}
if (allcr == 0)
{
alert("Error:You did not enter any credit values. GPA = N/A");
return 0;
}
gpa = allgr / allcr;
alert("GPA = " + gpa);
return 0;
}
<center>
<form name = "GPACalcForm">
<table border = "2" bgcolor = #bb8fce cellpadding = "5" cellspacing = "2">
<TH> </TH>
<TH>Grade</TH>
<TH>Credits</TH>
<TR>
<TD>IT 201</TD>
<TD><input type = "text" size = "5" name = "GR1" align = "top" maxlength = "5"></TD>
<TD><input type = "text" size = "5" name = "CR1" align = "top" maxlength = "5"></TD>
</TR>
<TR>
<TD>IT 202</TD>
<TD><input type = "text" size = "5" name = "GR2" align = "top" maxlength = "5"></TD>
<TD><input type = "text" size = "5" name = "CR2" align = "top" maxlength = "5"></TD>
</TR>
<TR>
<TD>IT 203</TD>
<TD><input type = "text" size = "5" name = "GR3" align = "top" maxlength = "5"></TD>
<TD><input type = "text" size = "5" name = "CR3" align = "top" maxlength = "5"></TD>
</TR>
<TR>
<TD>IT 204</TD>
<TD><input type = "text" size = "5" name = "GR4" align = "top" maxlength = "5"></TD>
<TD><input type = "text" size = "5" name = "CR4" align = "top" maxlength = "5"></TD>
</TR>
<TR>
<TD>IT 205</TD>
<TD><input type = "text" size = "5" name = "GR5" align = "top" maxlength = "5"></TD>
<TD><input type = "text" size = "5" name = "CR5" align = "top" maxlength = "5"></TD>
</TR>
<TR>
<TR align = "center">
<TD colspan = "3">
<input type = "button" value = "Calculate" name = "CalcButton" OnClick = "gpacalc()">
</TD>
</TR>
</table>
</form>
<br/>
<p> </p>
</center>
<br/>
I have made the following change in your code :-
if (ingr[x] == "")
break;
alert("Error: You did not enter a numeric credits value for subject. If the subject is worth 0 credits, then enter the number 0 in the field.");
to
if (ingr[x] == "") {
alert("Error: You did not enter a numeric credits value for subject. If the subject is worth 0 credits, then enter the number 0 in the field.");
break;
}
I am working on a Script for sorting boxes.
Here my problem.
In the code:
Size_XS = document.getElementById('Size_XS'+i).value*1;
seems to work without any problem.
While this one:
document.getElementById('Size_XS'+i).value = Size_XS;
will give me the error message: document.getElementById(...) is null or not an object.
if I change to:
document.getElementById('Size_XS1').value = Size_XS;
It all works, but then I cannot loop the file later and why does it work with i above?
My script below:
function calcbox(){
var count = document.getElementById('count').value*1;
count = count+1;
var box_num = 0;
var header = "<table style='border:#000 1px solid; background-color:#fff;'><tr><td width='25'><b>Box</b></td><td width='200'><b>Item name</b></td><td width='100'><b>Sizes</b></td><td width='250'><b>Pcs</b></td></tr>";
var output = header+document.getElementById('output').innerHTML;
var total_qty;
var box_qty;
var item_name;
var Size_XS=0;
var Size_S=0;
var Size_M=0;
var Size_L=0;
/*for(var i=1;i<count;i++){*/
var i=1;
total_qty = document.getElementById('total_qty'+i).value*1;
box_qty = document.getElementById('box_qty'+i).value*1;
item_name = document.getElementById('item_name'+i).value;
Size_XS = document.getElementById('Size_XS'+i).value*1;
Size_S = document.getElementById('Size_S'+i).value*1;
Size_M = document.getElementById('Size_M'+i).value*1;
Size_L = document.getElementById('Size_L'+i).value*1;
//Packing whole boxes
if(Size_XS>=box_qty){
var Box_count = parseInt(Size_XS/box_qty);
for(var i=1;i<=Box_count;i++){
box_num = box_num+1;
output = output+"<tr><td>"+box_num+"</td><td>"+item_name+"</td><td>S</td><td>"+box_qty+"</td></tr>";
}
Size_XS = Size_XS-(box_qty*Box_count);
alert(Size_XS);
document.getElementById('Size_XS'+i).value = Size_XS;
}
if(Size_S>=box_qty){
var Box_count = parseInt(Size_S/box_qty);
for(var i=1;i<=Box_count;i++){
box_num = box_num+1;
output = output+"<tr><td>"+box_num+"</td><td>"+item_name+"</td><td>S</td><td>"+box_qty+"</td></tr>";
}
Size_S = Size_S-(box_qty*Box_count);
document.getElementById('Size_S'+i).value = Size_S;
}
if(Size_M>=box_qty){
var Box_count = parseInt(Size_M/box_qty);
for(var i=1;i<=Box_count;i++){
box_num = box_num+1;
output = output+"<tr><td>"+box_num+"</td><td>"+item_name+"</td><td>M</td><td>"+box_qty+"</td></tr>";
}
Size_M = Size_M-(box_qty*Box_count);
document.getElementById('Size_M'+i).value = Size_M;
}
if(Size_L>=box_qty){
var Box_count = parseInt(Size_L/box_qty);
for(var i=1;i<=Box_count;i++){
box_num = box_num+1;
output = output+"<tr><td>"+box_num+"</td><td>"+item_name+" </td><td>L</td><td>"+box_qty+"</td></tr>";
}
Size_L = Size_L-(box_qty*Box_count);
document.getElementById('Size_L'+i).value = Size_L;
}
document.getElementById("output").innerHTML = output+"</table>";
document.getElementById("qty_boxes").value = box_num;
show('Volume_weight');
}
I'm getting my values from here in the HTML code:
<table>
<tr>
<td width="10">1</td>
<td width="120"><input id="item_name1" type="text" style="width:100px;" /></td>
<td width="80"><input id="box_qty1" type="text" style="width:30px;" /></td>
<td width="40"><input id="Size_XS1" type="text" style="width:30px;" onchange="totcalc(1);" /></td>
<td width="40"><input id="Size_S1" type="text" style="width:30px;" onchange="totcalc(1);" /></td>
<td width="40"><input id="Size_M1" type="text" style="width:30px;" onchange="totcalc(1);" /></td>
<td width="40"><input id="Size_L1" type="text" style="width:30px;" onchange="totcalc(1);" /></td>
<td width="60"><input id="total_qty1" type="text" style="width:50px;" /></td>
</tr>
</table>
You have used i for two different things in the code. Firstly as a suffix to input element id values, and secondly as a loop counter for boxes. After i is no longer equal to 1 after various loops complete, the HTML element lookup by suffixed id fails:
document.getElementById('Size_XS'+i).value = Size_XS;
occurs after
for(var i=1;i<=Box_count;i++){ // ...
Feel free to delete the question if this is the problem :D
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.