I have a problem with the following JavaScript code. It has an error alert said that table value is undefined. I'm trying to update the subtotal in each row by calculate price * qty.
function updateSubtotal() {
var subTotal = 0;
var tables = document.getElementsByTagName("table").rows;
var r = this.parentNode.parentNode.rowIndex;
var j = document.getElementsByTagName(".price").cellIndex;
var s = document.getElementsByTagName(".subtotal").cellIndex;
var price = tables[r].cells[j].value;
var quantity = document.getElementsByTagName("input").value;
var subAmount = price * quantity;
subTotal += Number(subAmount);
// set total for the row
document.getElementsByTagName('table').rows[r].cells[s].innerHTML = '$' + subTotal.toFixed(2);
}
updateTotal();
}
The original code that I tried to update:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
window.onload = setupCart;
function setupCart() {
var qtyInputs = document.querySelectorAll( 'input' );
for ( var i = 0; i < qtyInputs.length; i++ ) {
qtyInputs[ i ].oninput = updateSubtotal;
}
updateTotal();
}
function updateTotal() {
var total = 0;
var subTotals = document.querySelectorAll( '.subtotal' );
for ( var i = 0; i < subTotals.length; i++ ) {
var amount = subTotals[ i ].innerHTML.match( /[0-9]+.[0-9]+/ );
total += Number( amount );
}
document.querySelector( '#total' ).innerHTML = '$' + total.toFixed( 2 );
}
</script>
</head>
<body>
><table>
><tr>
><th>Description</th>
><th>Each</th>
><th>Qty</th>
><th>subtotal</th>
></tr>
<tr class="item">
<td class="description"><img src="red-shirt.jpg" alt="" />Red Crew Neck T-Shirt</td>
<td class="price">$15.00</td>
<td><input type="number" value="1" min="0" /></td>
<td class="subtotal">$15.00</td>
</tr>
<tr class="item">
<td class="description"><img src="tropical-shirt.jpg" alt="" />Blue Tropical Floral Print T-Shirt</td>
<td class="price">$25.00</td>
<td><input type="number" value="1" min="0" /></td>
<td class="subtotal">$25.00</td>
</tr>
<tr class="item">
<td class="description"><img src="black-sneakers.jpg" alt="" />Black Canvas Lace Up Sneakers</td>
<td class="price">$35.00</td>
<td><input type="number" value="1" min="0" /></td>
<td class="subtotal">$35.00</td>
</tr>
<tr class="item">
<td class="description"><img src="black-grey-jacket.jpg" alt="" />Black and Grey Hooded Jacket</td>
<td class="price">$40.00</td>
<td><input type="number" value="1" min="0" /></td>
<td class="subtotal">$40.00</td>
</tr>
<tr class="item">
<td class="description"><img src="black-sunglasses.jpg" alt="" />Black Retro Sunglasses</td>
<td class="price">$15.00</td>
<td><input type="number" value="1" min="0" /></td>
<td class="subtotal">$15.00</td>
</tr>
<tr class="cart-summary">
<td></td>
<td></td>
<th>Total:</th>
<td id="total"></td>
</tr>
</table>
</body>
</html>
The .getElementsByTagName() function returns a NodeList object. If you want the first <table> on the page, you'd use
document.getElementsByTagName("table")[0].rows ...
It would be better to fetch it just once at the start of the function:
var table = document.getElementsByTagName("table")[0];
to avoid having to re-traverse the DOM.
Maybe it's because document.getElementsByTagName doesn't return an element but a list of elements... you have to access the node you need like this document.getElementsByTagName("table")[0].rows
Related
Here's another problem encountered with js/html code. I typed some numbers at the top of the page, then after I pressed the button First Line, it will display the numbers I inputted in the first table row accordingly. If I press the button Last Line, I'd like it to display some numbers after getting done with some arithmetics, which is in the btn2 part in the js file, in the last table row of the page. I'd like to find out if it is the problem of innerHTML or valueAsNumber in the if statements, or the variables declared in the for loop not applicable in the later if statements, that caused the numbers in the last row cannot be displayed eventually.
The for loop and the if statement is intended for the page to scan the numbers inputted in the first row, do some arithmetics with them, and display them in the last row, in each respective cell. Is there any other way out to do so?
Thank you very much!
const tab = document.getElementById("tab");
const btn1 = document.getElementById('btn1');
const btn2 = document.getElementById('btn2');
var R1 = [R1C1, R1C2, R1C3, R1C4, R1C5, R1C6, R1C7, R1C8,
R1C9, R1C10, R1C11, R1C12, R1C13, R1C14, R1C15, R1C16];
var R2 = [R2C1, R2C2, R2C3, R2C4, R2C5, R2C6, R2C7, R2C8,
R2C9, R2C10, R2C11, R2C12, R2C13, R2C14, R2C15, R2C16];
btn1.addEventListener('click', () => {
for (var i = 0; i <= 15; i++) {
let row = tab.rows[1];
let c = row.cells[i];
let inpId = 'inp' + (i + 1);
let inpEl = document.getElementById(inpId);
c.innerHTML = inpEl.value;
}
});
btn2.addEventListener('click', () => {
for (var i = 0; i <= 15; i++) {
var r1c = R1[i].id;
var r2c = R2[i].id;
var r1El = document.getElementById(r1c);
var r2El = document.getElementById(r2c);
}
if (r1El.innerHTML > 0) {
var choices = [0, (r1El.valueAsNumber) % 7, (r1El.valueAsNumber + 2) % 7, (r1El.valueAsNumber - 2) % 7];
var x = Math.floor(Math.random() * choices.length);
if (choices[x] == choices.at(0)) {
r2El.innerHTML = choices[x];
} else if (choices[x] <= 0) {
r2El.innerHTML = choices[x] + 7;
}
}
});
th,
tr,
td {
border: 1px solid black;
padding: 5px;
width: 40px;
text-align: center;
}
<div class="container">
<div id="data">
<table id="inpdata">
<tr>
<td id="inpb1">Group 1</td>
<td id="inpb2">Group 2</td>
<td id="inpb3">Group 3</td>
<td id="inpb4">Group 4</td>
</tr>
<tr>
<td>
<input type="number" id="inp1" title="inp1">
<input type="number" id="inp2" title="inp2">
<input type="number" id="inp3" title="inp3">
<input type="number" id="inp4" title="inp4">
</td>
<td>
<input type="number" id="inp5" title="inp5">
<input type="number" id="inp6" title="inp6">
<input type="number" id="inp7" title="inp7">
<input type="number" id="inp8" title="inp8">
</td>
<td>
<input type="number" id="inp9" title="inp9">
<input type="number" id="inp10" title="inp10">
<input type="number" id="inp11" title="inp11">
<input type="number" id="inp12" title="inp12">
</td>
<td>
<input type="number" id="inp13" title="inp13">
<input type="number" id="inp14" title="inp14">
<input type="number" id="inp15" title="inp15">
<input type="number" id="inp16" title="inp16">
</td>
</tr>
</table>
<br>
<button id="btn1">First line</button>
<button id="btn2">Last line</button>
</div>
<div id="tables">
<table id="tab">
<tr>
<th colspan="4">Group 1</th>
<th colspan="4">Group 2</th>
<th colspan="4">Group 3</th>
<th colspan="4">Group 4</th>
</tr>
<tr>
<td id="R1C1"></td>
<td id="R1C2"></td>
<td id="R1C3"></td>
<td id="R1C4"></td>
<td id="R1C5"></td>
<td id="R1C6"></td>
<td id="R1C7"></td>
<td id="R1C8"></td>
<td id="R1C9"></td>
<td id="R1C10"></td>
<td id="R1C11"></td>
<td id="R1C12"></td>
<td id="R1C13"></td>
<td id="R1C14"></td>
<td id="R1C15"></td>
<td id="R1C16"></td>
</tr>
<tr>
<td id="R2C1"></td>
<td id="R2C2"></td>
<td id="R2C3"></td>
<td id="R2C4"></td>
<td id="R2C5"></td>
<td id="R2C6"></td>
<td id="R2C7"></td>
<td id="R2C8"></td>
<td id="R2C9"></td>
<td id="R2C10"></td>
<td id="R2C11"></td>
<td id="R2C12"></td>
<td id="R2C13"></td>
<td id="R2C14"></td>
<td id="R2C15"></td>
<td id="R2C16"></td>
</tr>
</table>
</div>
So you can Iterate the td by iterating the elements HTMLCollection property of the tr. Iterate two Iterables by using the index from one.
const tab = document.getElementById("tab");
const btn1 = document.getElementById('btn1');
const btn2 = document.getElementById('btn2');
const firstRow = tab.firstElementChild.children[1].children;
const secondRow = tab.firstElementChild.children[2].children;
btn1.addEventListener('click', () => {
for (var i = 0; i <= 7 /* <- This is a magic value - avoid these */; i++) {
let row = tab.rows[1];
let c = row.cells[i];
let inpId = 'inp' + (i + 1);
let inpEl = document.getElementById(inpId);
c.innerHTML = inpEl.value;
}
});
btn2.addEventListener('click', () => {
[...secondRow].forEach((el,index)=>{
//let group = Math.floor(index / 4);
let inp = parseInt(firstRow[index].innerText, 10);
if (!inp) return;
let choices = [0, inp, (inp + 2), (inp - 2)];
let x = (Math.floor(Math.random() * choices.length) + 7) % 7;
el.innerText = x;
})
});
th,
tr,
td {
border: 1px solid black;
padding: 5px;
width: 40px;
height: 1.5em;
text-align: center;
}
<div class="container">
<div id="data">
<table id="inpdata">
<tr>
<td id="inpb1">Group 1</td>
<td id="inpb2">Group 2</td>
</tr>
<tr>
<td>
<input type="number" id="inp1" title="inp1">
<input type="number" id="inp2" title="inp2">
<input type="number" id="inp3" title="inp3">
<input type="number" id="inp4" title="inp4">
</td>
<td>
<input type="number" id="inp5" title="inp5">
<input type="number" id="inp6" title="inp6">
<input type="number" id="inp7" title="inp7">
<input type="number" id="inp8" title="inp8">
</td>
</tr>
</table>
<br>
<button id="btn1">First line</button>
<button id="btn2">Last line</button>
</div>
<div id="tables">
<table id="tab">
<tr>
<th colspan="4">Group 1</th>
<th colspan="4">Group 2</th>
</tr>
<tr>
<td></td><td></td><td></td><td></td>
<td></td><td></td><td></td><td></td>
</tr>
<tr>
<td></td><td></td><td></td><td></td>
<td></td><td></td><td></td><td></td>
</tr>
</table>
</div>
Some additional advice:
I couldn't be bothered to clean up all of your code, next time please provide a Minimal Example, tree fields would have been plenty to ask the question.
Further please avoid magic numbers, like you use in your loops. Get the size of what you are iterating when you use it. This makes your code more flexible and reusable.
In the same vein: Please do not throw ids everywhere. They just beg to break your code if you ever try to reuse it somehow.
I am working on a form to create an invoice.
so basically, i have a button to create a table row where I can enter the code, name of product, notes, qty, price and discount. then automatically add the total price, by multiply the qty and subtracting the discount.
The problem I am having is to get the row index where the addition need to be worked. The first row it works but the second, third, etc... doesn't work.
I am asking here maybe there is some one that can find the problem. I am a beginner when it comes to javascript and basically learning while working on it, so any help it is really appreciated.
// Item Counter
var ic = 1;
// Remove an entry
function RemoveEntryFromList(entry) {
document.getElementById(entry).remove();
}
// Adds an entry into the "Added Items" list
function addEntryToList(p_code, p_name, p_sn, p_qty, p_price, p_discount, p_url, p_costPrice, p_qtyAvailable) {
var entry = document.createElement("tr");
entry.id = ("item-" + String(ic));
document.getElementById("list-table").tBodies[0].appendChild(entry);
p_price1 = parseFloat(p_price).toFixed(2);
p_costPrice1 = parseFloat(p_costPrice).toFixed(2);
entry.innerHTML = `<td><input value="${p_code}" /></td>
<td><input value="${p_name}" /></td>
<td><input value="${p_sn}" /></td>
<td><input type="text" id="qty" value="${p_qty}" oninput="calculate()" /></td>
<td><input type="text" id="price" step="0.01" min="0.00" value="${p_price1}" oninput="calculate()" /></td>
<td><input type="text" id="discount" value="${p_discount}" oninput="calculate()" /></td>
<td><input type="number" id="net_price" readonly /></td>
<td style="text-align: center;"><button onclick="RemoveEntryFromList('${entry.id}')"> X </button></td>
<td style="text-align: center; cursor: pointer;"><i class="fas fa-ellipsis-v"></i></td>`;
ic++;
}
function calculate() {
var calc_qty = document.getElementById('qty').value;
var calc_price = document.getElementById('price').value;
var discount = document.getElementById('discount').value;
var result = document.getElementById('net_price');
var calc_discount = calc_price * (discount / 100);
var calc_result = (calc_price - calc_discount) * calc_qty;
result.value = calc_result;
}
<div id="container">
<div id="list-sect">
<button id="add-custom-item-btn" onClick="addEntryToList('', '', '', '1', '0.00', '0');" style="height: 30px;">
<i class="fas fa-box-open"></i> Add New Entry
</button>
</div>
<table id="list-table">
<tr class="list-entry" style="height: 21px;">
<th width="80px">Code</th>
<th>Name</th>
<th>notes</th>
<th width="60px">Qty</th>
<th width="76px">Price</th>
<th width="65px">Disc.(%)</th>
<th width="76px">Total Price</th>
<th colspan="2">Remove</th>
</tr>
</table>
</div>
Don't use id's in your generated code, id's have to be unique. I changed them to classes. I also changed the calculate function so the target element is given as a parameter. In the calculate function the correct elements are found based on the element in the parameter.
But it's a pretty ugly way of handling this. I recommend rewrite it so you do event delegation on your table like in the function below. If you don't want that then see the bottom snippet.
//Event delgation from the table as replacement of the calculate function
document.querySelector('#list-table').addEventListener('input', function(e) {
//Element that triggered
let target = e.target;
//check if the target has the class of one of our input elements that we want to use for (re)calculation
if (target.classList.contains('qty') ||
target.classList.contains('price') ||
target.classList.contains('discount') ||
target.classList.contains('net_price')
) {
//(re)calculate
var targetRow = target.parentElement.parentElement;
var calc_qty = targetRow.querySelector('.qty').value;
var calc_price = targetRow.querySelector('.price').value;
var discount = targetRow.querySelector('.discount').value;
var result = targetRow.querySelector('.net_price');
var calc_discount = calc_price * (discount / 100);
var calc_result = (calc_price - calc_discount) * calc_qty;
result.value = calc_result;
}
});
// Item Counter
var ic = 1;
// Remove an entry
function RemoveEntryFromList(entry) {
document.getElementById(entry).remove();
}
// Adds an entry into the "Added Items" list
function addEntryToList(p_code, p_name, p_sn, p_qty, p_price, p_discount, p_url, p_costPrice, p_qtyAvailable) {
var entry = document.createElement("tr");
entry.id = ("item-" + String(ic));
document.getElementById("list-table").tBodies[0].appendChild(entry);
p_price1 = parseFloat(p_price).toFixed(2);
p_costPrice1 = parseFloat(p_costPrice).toFixed(2);
entry.innerHTML = `<td><input value="${p_code}" /></td>
<td><input value="${p_name}" /></td>
<td><input value="${p_sn}" /></td>
<td><input type="text" class="qty" value="${p_qty}" /></td>
<td><input type="text" class="price" step="0.01" min="0.00" value="${p_price1}" /></td>
<td><input type="text" class="discount" value="${p_discount}" /></td>
<td><input type="number" class="net_price" readonly /></td>
<td style="text-align: center;"><button onclick="RemoveEntryFromList('${entry.id}')"> X </button></td>
<td style="text-align: center; cursor: pointer;"><i class="fas fa-ellipsis-v"></i></td>`;
ic++;
}
<div id="container">
<div id="list-sect">
<button id="add-custom-item-btn" onClick="addEntryToList('', '', '', '1', '0.00', '0');" style="height: 30px;">
<i class="fas fa-box-open"></i> Add New Entry
</button>
</div>
<table id="list-table">
<tr class="list-entry" style="height: 21px;">
<th width="80px">Code</th>
<th>Name</th>
<th>notes</th>
<th width="60px">Qty</th>
<th width="76px">Price</th>
<th width="65px">Disc.(%)</th>
<th width="76px">Total Price</th>
<th colspan="2">Remove</th>
</tr>
</table>
</div>
Original answer:
// Item Counter
var ic = 1;
// Remove an entry
function RemoveEntryFromList(entry) {
document.getElementById(entry).remove();
}
// Adds an entry into the "Added Items" list
function addEntryToList(p_code, p_name, p_sn, p_qty, p_price, p_discount, p_url, p_costPrice, p_qtyAvailable) {
var entry = document.createElement("tr");
entry.id = ("item-" + String(ic));
document.getElementById("list-table").tBodies[0].appendChild(entry);
p_price1 = parseFloat(p_price).toFixed(2);
p_costPrice1 = parseFloat(p_costPrice).toFixed(2);
entry.innerHTML = `<td><input value="${p_code}" /></td>
<td><input value="${p_name}" /></td>
<td><input value="${p_sn}" /></td>
<td><input type="text" class="qty" value="${p_qty}" oninput="calculate(this)" /></td>
<td><input type="text" class="price" step="0.01" min="0.00" value="${p_price1}" oninput="calculate(this)" /></td>
<td><input type="text" class="discount" value="${p_discount}" oninput="calculate(this)" /></td>
<td><input type="number" class="net_price" readonly /></td>
<td style="text-align: center;"><button onclick="RemoveEntryFromList('${entry.id}')"> X </button></td>
<td style="text-align: center; cursor: pointer;"><i class="fas fa-ellipsis-v"></i></td>`;
ic++;
}
function calculate(element) {
var calc_qty = element.parentElement.parentElement.querySelector('.qty').value;
var calc_price = element.parentElement.parentElement.querySelector('.price').value;
var discount = element.parentElement.parentElement.querySelector('.discount').value;
var result = element.parentElement.parentElement.querySelector('.net_price');
var calc_discount = calc_price * (discount / 100);
var calc_result = (calc_price - calc_discount) * calc_qty;
result.value = calc_result;
}
<div id="container">
<div id="list-sect">
<button id="add-custom-item-btn" onClick="addEntryToList('', '', '', '1', '0.00', '0');" style="height: 30px;">
<i class="fas fa-box-open"></i> Add New Entry
</button>
</div>
<table id="list-table">
<tr class="list-entry" style="height: 21px;">
<th width="80px">Code</th>
<th>Name</th>
<th>notes</th>
<th width="60px">Qty</th>
<th width="76px">Price</th>
<th width="65px">Disc.(%)</th>
<th width="76px">Total Price</th>
<th colspan="2">Remove</th>
</tr>
</table>
</div>
in order for your code to work using document.getElementById("list-table").tBodies[0].appendChild(entry); you need to enclose your rows (<tr>) inside a <tbody> </tbody>.
also i'd change your entry.innerHTML = (...) to add each td as a new createElement() inside entry.
I am unsure of what I have done wrong in my simple sales tax calculator. When I press submit I want a dollar amount of the item cost plus sales tax to be shown but instead I see total tip $functionround(){[native code]}.
//calculation
var total = (itemCost * salesTax + itemCost);
total = Math.round
total = Math.round
In the line above you are assigning the value of the function Math.round to the variable total. Instead you probably want to assign the value returned by the function Math.round to your total variable like this:
total = Math.round(total)
You should consider those codes on the calculation. Here is a simple tax calculator and it works well:
function fmtPrice(value) {
result="$"+Math.floor(value)+".";
var cents=100*(value-Math.floor(value))+0.5;
result += Math.floor(cents/10);
result += Math.floor(cents%10);
return result;
}
function compute() {
var unformatted_tax = (document.forms[0].cost.value)*(document.forms[0].tax.value);
document.forms[0].unformatted_tax.value=unformatted_tax;
var formatted_tax = fmtPrice(unformatted_tax);
document.forms[0].formatted_tax.value=formatted_tax;
var cost3= eval( document.forms[0].cost.value );
cost3 += eval( (document.forms[0].cost.value)*(document.forms[0].tax.value) );
var total_cost = fmtPrice(cost3);
document.forms[0].total_cost.value=total_cost;
}
function resetIt() {
document.forms[0].cost.value="19.95"; // cost of product
document.forms[0].tax.value=".06"; // tax value
document.forms[0].unformatted_tax.value="";
document.forms[0].formatted_tax.value="";
document.forms[0].total_cost.value="";
}
<CENTER>
<FORM>
<TABLE BORDER=2 WIDTH=300 CELLPADDING=3>
<TR>
<TD align="center"><FONT SIZE=+1><STRONG>Cost</STRONG></FONT>
<TD align="center"><FONT SIZE=+1><STRONG>Tax</STRONG></FONT>
</TR>
<TR>
<TD align="center"><INPUT TYPE="text" NAME="cost" VALUE="19.95" SIZE=10>
<TD align="center"><INPUT TYPE="text" NAME="tax" VALUE=".06" SIZE=10>
</TR>
</TABLE>
<BR>
<TABLE BORDER=1 WIDTH=600 CELLPADDING=3>
<TR>
<TD align="center"><FONT SIZE=+1><STRONG>Unformatted Tax</STRONG></FONT>
<TD align="center"><FONT SIZE=+1><STRONG>Formatted Tax</STRONG></FONT>
<TD align="center"><FONT SIZE=+1><STRONG>TOTAL COST</STRONG></FONT>
</TR>
<TR>
<TD align="center"><INPUT TYPE="text" NAME="unformatted_tax" SIZE=15>
<TD align="center"><INPUT TYPE="text" NAME="formatted_tax" SIZE=15>
<TD align="center"><INPUT TYPE="text" NAME="total_cost" SIZE=15>
</TR>
</TABLE>
<BR>
<TABLE BORDER=0 WIDTH=400 CELLPADDING=5>
<TR>
<TD align="center"><INPUT TYPE="reset" VALUE="RESET" onClick="resetIt()">
<TD align="center"><INPUT TYPE="button" VALUE="COMPUTE" onclick="compute()">
</TR>
</TABLE>
</CENTER>
As noted you need to return the total of hte Math.round - but you also need to parse the values into numbers) and then you also have to remember that the sales tax is a percentage - so it has to be divided by 100.
I have amended your logic to
a) parse the values of the inputs into numbers using parseInt()
b) resolve the math.round() issue
c) get the sales tax value by multiplying the item cost by the sales tax percentage ... itemCost * (salesTax/100)
d) add the sales tax value to the item cost ... item cost + (itemCost * (salesTax/100))...
//Function
function calculateTip() {
var itemCost = parseInt(document.getElementById("itemCost").value);
var salesTax = parseInt(document.getElementById("salesTax").value);
//enter values window
if (itemCost === "" || salesTax == "") {
window.alert("Please enter the values!");
return;
}
//calculation
var total = Math.round(itemCost + (itemCost * salesTax/100));
//display amount
document.getElementById("totalTip").style.display = "block";
document.getElementById("amount").innerHTML = total;
}
//Hide Tip Amount and call our function with a button
document.getElementById("totalTip").style.display = "none";
document.getElementById("submit").onclick = function() {
calculateTip();
};
</head>
<body id="color">
<div class="container" id="contain">
<div class="text-center">
<h1>Sales Tax Calculator</h1>
<p> Amount Before Tax?</p>
$ <input id="itemCost" type="text" placeholder="item cost">
<p>Sales Tax Percentage?</p>
<input id="salesTax" type="text" placeholder="sales tax percent"><br><br>
<button type="submit" id="submit">submit</button>
</div>
<div class="container" ID="totalTip">
<div class="text-center">
<p>Total Tip</p>
<sup>$</sup><span id="amount">0.00</span>
</div>
</div>
</div>
<script type="text/javascript" src="javascript.js"></script>
</body>
I try to get result from html table witch excepted only numbers i check them throw if statement if variable 1 bigger than variable 2 print content and that works good.
Now i am trying in the if statement to print variable 1 - variable 2 but it doesn't wanna work.
Here is the snippet:
$(document).ready(function() {
var vastInkomen = 0;
$('.txtBox').keyup(function() {
vastInkomen = 0;
$('.txtBox').each(function() {
var txtBoxVal = $(this).val();
vastInkomen += Number(txtBoxVal);
});
$('#vastInkomen').val(vastInkomen);
writeResult();
});
var vastLasten = 0;
$('.vast_lasten').keyup(function() {
vastLasten = 0;
$('.vast_lasten').each(function() {
var vastLastenVal = $(this).val();
vastLasten += Number(vastLastenVal);
});
$('#vastLasten').val(vastLasten);
writeResult();
});
function writeResult() {
if (vastInkomen !== 0 && vastLasten !== 0) {
if (vastInkomen > vastLasten) {
$('#result').text("Some text and work good!") +
vastLasten - vastInkomen;
} else if (vastInkomen < vastLasten) {
//$('#result-amount').console(vastInkomen -vastLasten);
$('#result').text("some text and work good.");
}
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td>content1</td>
<td><input class="txtBox" type="number" name="content2" />
</td>
</tr>
<tr>
<td>content3</td>
<td><input class="txtBox" type="number" name="content3" />
</td>
</tr>
<tr>
<td>content4</td>
<td>
<input class="txtBox" type="number" name="content4" />
</td>
</tr>
</table>
<table>
<tr>
<td>content</td>
<td><input class="vast_lasten" type="number" name="content" /></td>
</tr>
<tr>
<td>content1</td>
<td><input class="vast_lasten" type="number" name="content1" /></td>
</tr>
<tr>
<td>content2</td>
<td><input class="vast_lasten" type="texnumber" name="content2" /></td>
</tr>
</table>
<div class="col">
<h3>Het resultaat is:</h3>
<p id="result"></p>
</div>
This will work:
var result = vastLasten - vastInkomen;
$('#result').text("Some text and work good!" + result);
You can use .text() to set the content of an element, but everything should be within the parenthesis.
I added an extra variable result because you cannot use + and - both here; it will result in NaN as it will try to sum the values.
This works as well:
$('#result').text("Some text and work good!" + (vastLasten - vastInkomen));
I am in the process of writing a webpage. I have everything done that is needed, however, when you enter any quantity over 30 it will make the id = "shipping" color red. It does this but it does it for anything less than 30 as well. Also I am having trouble with my submit button sending off to a server/url. Any help is appreciated! I will attach my code!
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title> Widgets R' Us </title>
<style>
table,
td {
border: 1px solid black;
}
</style>
<script type="text/javascript">
//Check if non -number or a negative number
function realNumber() {
var qty1 = document.getElementById("Quantity1").value;
var qty2 = document.getElementById("Quantity2").value;
var qty3 = document.getElementById("Quantity3").value;
//isNaN is a predetermined function
if ((isNaN(qty1) || qty1 < 0) || (isNaN(qty2) || qty2 < 0) || (isNaN(qty3) || qty3 < 0)) {
alert("The quantity given is not a real number or is a negative number!");
return false; //Will not allow for data to go to server.
} else {
return true;
}
}
function total() {
var p1 = document.getElementById("Price1").value; //Value is referenced to the input tag
var p2 = document.getElementById("Price2").value;
var p3 = document.getElementById("Price3").value;
var qty1 = document.getElementById("Quantity1").value;
var qty2 = document.getElementById("Quantity2").value;
var qty3 = document.getElementById("Quantity3").value;
var over = qty1 + qty2 + qty3;
if (realNumber()) {
var totals = (p1 * qty1) + (p2 * qty2) + (p3 * qty3);
var yes = (totals).toFixed(2);
document.getElementById("ProductTotal").innerHTML = "$" + yes;
if (over > 30) {
document.getElementById("shipping").style.color = "red";
} else {
document.getElementById("shipping").style.color = "black";
}
}
}
function checkOut() {
if (total()) {
if ((document.getElementById("shipping").style.color == "red") &&
(document.getElementById("extra").checked)) {
return true;
}
}
return false;
}
</script>
</head>
<body>
<div>
<h1><b><big> Widgets R' Us </b></strong>
</h1>
<h2><b> Order/Checkout </b></h2>
<form name "widgets" onsubmit="return checkOut();" action="https://www.reddit.com/" method="get">
<div id="mainTable">
<table>
<tr>
<td>Widget Model:</td>
<td>37AX-L
<td>
</tr>
<tr>
<td>Price per Unit:</td>
<td>$12.45 <input type="hidden" id="Price1" name="Price1" value="12.45" /</td>
</tr>
<tr>
<td>State:</td>
<td>Regular</td>
</tr>
<tr>
<td>Quantity:</td>
<td> <input type="text" id="Quantity1" name="Quantity1" value="0" /</td>
</tr>
</table>
<tr>
<td> </td>
<td> </td>
</tr>
<table>
<tr>
<td>Widget Model:</td>
<td>42XR-J</td>
</tr>
<tr>
<td>Price per Unit:</td>
<td>$15.34 <input type="hidden" id="Price2" name="Price2" value="15.34" /></td>
</tr>
<tr>
<td>State:</td>
<td>Regular</td>
</tr>
<tr>
<td>Quantity:</td>
<td> <input type="text" id="Quantity2" name="Quantity2" value="0" /></td>
</tr>
</table>
<tr>
<td> </td>
<td> </td>
</tr>
<table>
<tr>
<td>Widget Model:</td>
<td>93ZZ-A</td>
</tr>
<tr>
<td>Price per Unit:</td>
<td>$28.99 <input type="hidden" id="Price3" name="Price3" value="28.99" /></td>
</tr>
<tr>
<td>State:</td>
<td>Regular</td>
</tr>
<tr>
<td>Quantity:</td>
<td> <input type="text" id="Quantity3" name="Quantity3" value="0" /></td>
</tr>
</table>
<tr>
<td> </td>
<td> </td>
</tr>
<table>
<tr>
<td>Product Total:</td>
<td>
<p id="ProductTotal"> 0 </p>
</td>
</tr>
<tr>
<td> <input type="checkbox" id="extra" name="extra"> </td>
<td>
<p id="shipping">If the quantity exceeds 30 units, there will be extra shipping!</p>
</td>
</tr>
</table>
</div>
<tr>
<td> <input type="Submit" value="Submit" /> </td>
<td> <input type="button" value="Calculate" onClick="total()" /> </td>
</tr>
</form>
</body>
</html>
Problem with your values qty1,qty2,qty3. these values are reading as string. so instead of addding these values , its concatinating the strings. replace
var qty1 = document.getElementById("Quantity1").value;
var qty2 = document.getElementById("Quantity2").value;
var qty3 = document.getElementById("Quantity3").value;
with
var qty1 = parseInt(document.getElementById("Quantity1").value);
var qty2 = parseInt(document.getElementById("Quantity2").value);
var qty3 = parseInt(document.getElementById("Quantity3").value);
It will Solve your problem with 'Red'.
For the submit button, function total() is not returning anything. so change something like
function total() {
var p1 = document.getElementById("Price1").value; //Value is referenced to the input tag
var p2 = document.getElementById("Price2").value;
var p3 = document.getElementById("Price3").value;
var qty1 = parseInt(document.getElementById("Quantity1").value);
var qty2 = parseInt(document.getElementById("Quantity2").value);
var qty3 = parseInt(document.getElementById("Quantity3").value);
var over = qty1 + qty2 + qty3;
if (realNumber()) {
var totals = (p1 * qty1) + (p2 * qty2) + (p3 * qty3);
var yes = (totals).toFixed(2);
document.getElementById("ProductTotal").innerHTML = "$" + yes;
if (over > 30) {
document.getElementById("shipping").style.color = "red";
return true;
} else if(over>0) {
document.getElementById("shipping").style.color = "black";
return true;
}else{
document.getElementById("shipping").style.color = "black";
return false;
}
}
}
and checkout() as
function checkOut() {
if (total()) {
if (((document.getElementById("shipping").style.color == "red") &&
(document.getElementById("extra").checked))||
(document.getElementById("shipping").style.color != "red")) {
return true;
}
}
return false;
}
Replace
var over = qty1 + qty2 + qty3;
With
var over = parseInt(qty1) + parseInt(qty2) + parseInt(qty3);
There were some minor HTML errors but the real issue is that numeric strings were being concatenated. So, to get the quantity values you need to use parseInt() to extract the integer value so that math is performed instead of string concatenation. Also, it's a little odd that the user has to click the Calculate Button in order to see a total. The button does work correctly, but is this what you really want?
One more thing, as tempting as it may be to directly alter the color of elements with JavaScript, in terms of keeping the code more robust, it is preferable to simply change the class name as the code does in this example since I created two classes in the CSS for this purpose.
The form now submits as long as the checkbox is unchecked and the units do not exceed 30. I changed the method to "post" and adjusted the true/false return statements in checkOut(). Note when data is submitted using the POST method, then no form data appears appended to the URL; for more info see here. I also altered the totals() function so that now it returns a value, namely the total price.
var d = document;
d.g = d.getElementById;
var qty = [0, 0, 0, 0];
var shipping = d.g("shipping");
function realNumber() {
var qtyInvalid = [0, 0, 0, 0];
for (let i = 1, max = qtyInvalid.length; i < max; i++) {
qtyInvalid[i] = (isNaN(qty[i]) || qty[i] < 0);
}
if (qtyInvalid[1] || qtyInvalid[2] || qtyInvalid[3]) {
console.log("The quantity given is not a real number or is a negative number!");
return false;
}
return true;
}
function total() {
var over = 0;
var price = [0, 0, 0, 0];
for (j = 1, max = price.length; j < max; j++) {
price[j] = d.g("Price" + j + "").value;
qty[j] = d.g("Quantity" + j + "").value;
}
var totals = 0;
var yes = 0;
const radix = 10;
for (q = 1, max = qty.length; q < max; q++) {
over += parseInt(qty[q], radix)
}
//console.log(over);
if (!realNumber()) {
return false;
}
for (let k = 1, max2 = price.length; k < max2; k++) {
totals += (price[k] * qty[k]);
}
yes = (totals).toFixed(2);
d.g("ProductTotal").innerHTML = "$" + yes;
shipping.className = (over > 30) ? "red" : "black";
return totals;
} // end total
function checkOut() {
var retval = false;
var shippingIsRed = (shipping.className == "red");
var extraChecked = d.g("extra").checked;
if ( total() ) {
retval = (!shippingIsRed && !extraChecked)? true : false;
}
return retval;
} //end checkout
h1 {
font: 200% Arial, Helvetica;
font-weight: bold;
}
h2 {
font-weight: bold;
}
table,
td {
border: 1px solid black;
}
p.red {
color: #f00;
}
p.black {
color: #000;
}
<div>
<h1>Widgets R' Us</h1>
<h2>Order/Checkout</h2>
<form name="widgets" onsubmit="return checkOut()" action="https://www.example.com/" method="post">
<div id="mainTable">
<table>
<tr>
<td>Widget Model:</td>
<td>37AX-L
<td>
</tr>
<tr>
<td>Price per Unit:</td>
<td>$12.45 <input type="hidden" id="Price1" name="Price1" value="12.45" </td>
</tr>
<tr>
<td>State:</td>
<td>Regular</td>
</tr>
<tr>
<td>Quantity:</td>
<td> <input type="text" id="Quantity1" name="Quantity1" value="0" </td>
</tr>
</table>
<tr>
<td> </td>
<td> </td>
</tr>
<table>
<tr>
<td>Widget Model:</td>
<td>42XR-J</td>
</tr>
<tr>
<td>Price per Unit:</td>
<td>$15.34 <input type="hidden" id="Price2" name="Price2" value="15.34"></td>
</tr>
<tr>
<td>State:</td>
<td>Regular</td>
</tr>
<tr>
<td>Quantity:</td>
<td> <input type="text" id="Quantity2" name="Quantity2" value="0"></td>
</tr>
</table>
<tr>
<td> </td>
<td> </td>
</tr>
<table>
<tr>
<td>Widget Model:</td>
<td>93ZZ-A</td>
</tr>
<tr>
<td>Price per Unit:</td>
<td>$28.99 <input type="hidden" id="Price3" name="Price3" value="28.99"></td>
</tr>
<tr>
<td>State:</td>
<td>Regular</td>
</tr>
<tr>
<td>Quantity:</td>
<td> <input type="text" id="Quantity3" name="Quantity3" value="0"></td>
</tr>
</table>
<tr>
<td> </td>
<td> </td>
</tr>
<table>
<tr>
<td>Total Price:</td>
<td>
<p id="ProductTotal"> 0 </p>
</td>
</tr>
<tr>
<td> <input type="checkbox" id="extra" name="extra"> </td>
<td>
<p id="shipping" class="black">If the quantity exceeds 30 units, there will be extra shipping!</p>
</td>
</tr>
</table>
</div>
<tr>
<td> <input type="Submit" value="Submit" /> </td>
<td> <input type="button" value="Calculate" onClick="total()"> </td>
</tr>
</form>
I also removed some unnecessary repetitive code that fetches the quantity values, taking advantage of JavaScript closures and for-loops.