JavaScript - HTML5 data attributes - javascript

I've looked around on the web for an answer to my question. Found lots of scripts that I've copied and messed around with but can't get it working properly.
When I run it, my script below initially works but then displays 'NaN'.
I'm trying to create a simple order form that uses JavaScript to dynamically update and display the order total.
Each item for sale has an input (type=number) tag that contains the item's price in a 'data-price' attribute.
What I'm trying to do is grab the price out of the data-price attribute and use it in a JS script to display a total.
Users can enter a quantity into text field and the TOTAL text field should automatically update with correct 'running total'.
Would appreciate any advice as to where I'm going wrong. I've used JavaScript (as opposed to jQuery) because I'm more familiar with the syntax.
<script>
function calculateTotal(frm) {
var order_total = 0
for (var i=0; i < frm.elements.length; ++i) {
form_field = frm.elements[i];
item_price = form_field.dataset.pric);
item_quantity = form_field.value;
if (item_quantity >= 0) {
order_total += item_quantity * item_price;
}
}
frm.total.value = round_decimals(order_total, 2);
}
function round_decimals(original_number, decimals) {
var result1 = original_number * Math.pow(10, decimals);
var result2 = Math.round(result1);
var result3 = result2 / Math.pow(10, decimals);
return result3.toFixed(2);
}
</script>
</head>
<body>
<form id="order-form">
<table cellpadding="8" align="center">
<tr>
<td align="left" width="150">Image</td>
<td align="left">Description</td>
<td align="left">Price</td>
<td align="left">Quantity</td>
</tr>
<tr>
<td align="left"><img src="http://placehold.it/150x200"></td>
<td align="left">Poster</td>
<td align="left">$24.00</td>
<td align="left"><input type="number" data-price="24" min="0" max="50" step="1" value="0" onChange="calculateTotal(this.form)"></td>
</tr>
<tr>
<td align="left"><img src="http://placehold.it/150x200"></td>
<td align="left"> T-shirt</td>
<td align="left">$66.00</td>
<td align="left"><input type="number" data-price="65" min="0" max="50" step="1" value="0" onChange="calculateTotal(this.form)"></td>
</tr>
<tr>
<td align="left"><img src="http://placehold.it/150x200"></td>
<td align="left"> Bag</td>
<td align="left">$120.00</td>
<td align="left"><input type="number" data-price="120" min="0" max="50" step="1" value="0" onChange="calculateTotal(this.form)"></td>
</tr>
<tr>
<td></td>
<td></td>
<td>TOTAL:</td>
<td align="right"><input type="text" name="total" size="6" onFocus="this.form.elements[0].focus()"></td>
</tr>
</table>
</form>
</div>

You have a typo in the sample code.
item_price = form_field.dataset.pric);
should probably be
item_price = form_field.dataset.price;
Apart from that, NaN is caused by the fact that you're also taking into account the value of the 'total' field when you run the function calculateTotal(). But that field does not have a data-price attribute so you're multiplying undefined with a number, resulting in NaN.
You need to add an extra check if there is a 'data-price' attribute:
function calculateTotal(frm) {
var order_total = 0;
for (var i=0; i < frm.elements.length; ++i) {
form_field = frm.elements[i];
if(typeof(form_field.dataset.price) != 'undefined') {
item_price = form_field.dataset.price;
item_quantity = form_field.value;
if (item_quantity >= 0) {
order_total += item_quantity * item_price;
}
}
}
frm.total.value = round_decimals(order_total, 2);
}

Related

Making a for loop to calculate specific cells then writing result in the last cell in row

I'm very new to JS and I'm trying to learn for loops and in this case, I want to turn this into a for loop if possible. I want to calculate a static number string in cell 3, times the input number in cell 4, and output the result to a new cell 5 that has been created in the loop. Any help is much appreciated
var table = document.getElementById("table");
var Row1 = table.rows[1],
cell1 = Row1.insertCell(5);
var Row2 = table.rows[2],
cell2 = Row2.insertCell(5);
var Row3 = table.rows[3],
cell3 = Row3.insertCell(5);
var Row4 = table.rows[4],
cell4 = Row4.insertCell(5);
var Row5 = table.rows[5],
cell5 = Row5.insertCell(5);
var Row6 = table.rows[6],
cell6 = Row6.insertCell(5);
var x1 = table.rows[1].cells[4].getElementsByTagName('input')[0].value;
var y1 = table.rows[1].cells[3].innerHTML;
cell1.innerHTML = y1 * x1;
var x2 = table.rows[2].cells[4].getElementsByTagName('input')[0].value;
var y2 = table.rows[2].cells[3].innerHTML;
cell2.innerHTML = y2 * x2;
var x3 = table.rows[3].cells[4].getElementsByTagName('input')[0].value;
var y3 = table.rows[3].cells[3].innerHTML;
cell3.innerHTML = y3 * x3;
var x4 = table.rows[4].cells[4].getElementsByTagName('input')[0].value;
var y4 = table.rows[4].cells[3].innerHTML;
cell4.innerHTML = y4 * x4;
var x5 = table.rows[5].cells[4].getElementsByTagName('input')[0].value;
var y5 = table.rows[5].cells[3].innerHTML;
cell5.innerHTML = y5 * x5;
var x6 = table.rows[6].cells[4].getElementsByTagName('input')[0].value;
var y6 = table.rows[6].cells[3].innerHTML;
cell6.innerHTML = y6 * x6;
These don't need to be in functions but just to make it easier to read
function createCells() {
cells = []
for (let i = 1; i < 7; i++) {
var cells[i] = table.rows[i].insertCell(5)
}
}
function calculate() {
for
let (i = 1; i < 7; i++) {
var x = table.rows[i].cells[4].getElementsByTagName('input')[0].value;
var y = table.rows[i].cells[3].innerHTML;
cells[i].innerHTML = (y * x);
}
}
A short answer using a simple for-loop is this:
Loop through every row
For each row, multiply quantity with price
Output total in same row
Since we basically always want to have a "total"-field in every row, we can add it in the HTML directly.
And since we know the position of the price-element and quantity-element, we can access them using fixed values as indices.
var rows = document.querySelectorAll("#pricetable tbody tr");
for (var i = 0; i < rows.length; ++i) {
var price = rows[i].children[3].innerHTML;
var quantity = rows[i].children[4].children[0].value;
var total = price * quantity; // Implicit type-casting to numbers
rows[i].children[5].innerHTML = total;
}
<table id="pricetable">
<thead>
<tr>
<th>Number</th>
<th>Product</th>
<th>Brand</th>
<th>Price</th>
<th>Quantity</th>
<th>Total</th>
</tr>
</thead>
<tbody>
<tr>
<td>23456789</td>
<td>Phone</td>
<td>Apple</td>
<td>6500</td>
<td>
<input type="text" size="3" value="1" />
</td>
<td></td>
</tr>
<tr>
<td>22256289</td>
<td>Phone</td>
<td>Samsung</td>
<td>6200</td>
<td>
<input type="text" size="3" value="1" />
</td>
<td></td>
</tr>
<tr>
<td>24444343</td>
<td>Phone</td>
<td>Huawei</td>
<td>4200</td>
<td>
<input type="text" size="3" value="1" />
</td>
<td></td>
</tr>
<tr>
<td>19856639</td>
<td>Tablet</td>
<td>Apple</td>
<td>4000</td>
<td>
<input type="text" size="3" value="1" />
</td>
<td></td>
</tr>
<tr>
<td>39856639</td>
<td>Tablet</td>
<td>Samsung</td>
<td>2800</td>
<td>
<input type="text" size="3" value="1" />
</td>
<td></td>
</tr>
<tr>
<td>12349862</td>
<td>Tablet</td>
<td>Huawei</td>
<td>3500</td>
<td>
<input type="text" size="3" value="1" />
</td>
<td></td>
</tr>
</tbody>
</table>
Note: When changing the position of those elements (e.g. by add a new column infront of them), their index would shift. That would make you have to update the indices in the JS-file manually.
You can make this easier for yourself by using this simple "trick":
Add specific classes to the elements (e.g. .price, .quantity, .total), allowing you to easily find them using Element.querySelector().
Note: The script only runs once, the first time the page is loaded. That means, inputting a different quantity won't update the "total"-field. For that, we need an EventListener.
Another approach
By observing the for-loop, we can see:
We access only one row for each iteration
The order in which we access each row is irrelevant
Since both these points are checked, we can use a for...of-loop (also called foreach-loop or enhanced for-loop). A for...of-loop is (in my opinion) easier to read, and tells what we checked using the list above by itself.
Note: Be wary of the difference of the for...of-loop and the for...in-loop.
Now, we could calculate the total right then and there in the loop, but thinking ahead, we want to perform the same calculation again when inputting a new quantity-value. We can reduce the duplicate code by making the calculation a Function updateRowTotal(), making the code easier to debug and understand.
To actually update the total when entering a new quantity-value, we can use an EventListener that calls a function automatically when a new value is entered into the <input>-field (by calling updateRowTotal(evt.target.closest("tr"))).
function clamp(min, value, max) {
return Math.max(min, Math.min(value, max));
}
for (let row of document.querySelectorAll("#pricetable tbody tr")) {
updateRowTotal(row);
row.querySelector("input.quantity").addEventListener("input", evt => {
// Add '/*' before this comment to "remove" this extra part
// The 5 lines below are to clamp 'value' between 'min' and 'max'
let min = parseInt(evt.target.getAttribute("min"));
let max = parseInt(evt.target.getAttribute("max"));
if (isNaN(min)) min = Number.MIN_SAFE_INTEGER;
if (isNaN(max)) max = Number.MAX_SAFE_INTEGER;
evt.target.value = clamp(min, evt.target.value, max);
// */
updateRowTotal(evt.target.closest("tr"));
});
}
function updateRowTotal(row) {
row.querySelector(".total").innerHTML = row.querySelector(".price").innerHTML * row.querySelector(".quantity").value;
}
<table id="pricetable">
<thead>
<tr>
<th>Price</th>
<th>Quantity</th>
<th>Row-Total</th>
</tr>
</thead>
<tbody>
<tr>
<td class="price">6500</td>
<td>
<input class="quantity" type="number" min="0" max="999" value="1" />
</td>
<td class="total"></td>
</tr>
<tr>
<td class="price">6200</td>
<td>
<input class="quantity" type="number" min="0" max="999" value="1" />
</td>
<td class="total"></td>
</tr>
<tr>
<td class="price">4200</td>
<td>
<input class="quantity" type="number" min="0" max="999" value="1" />
</td>
<td class="total"></td>
</tr>
<tr>
<td class="price">4000</td>
<td>
<input class="quantity" type="number" min="0" max="999" value="1" />
</td>
<td class="total"></td>
</tr>
<tr>
<td class="price">2800</td>
<td>
<input class="quantity" type="number" min="0" max="999" value="1" />
</td>
<td class="total"></td>
</tr>
<tr>
<td class="price">3500</td>
<td>
<input class="quantity" type="number" min="0" max="999" value="1" />
</td>
<td class="total"></td>
</tr>
</tbody>
</table>
Sidenote
Making the <input>-field of type="number" prevents any non-numeric character to be entered.
And since the min- and max-attributes only prevent form-submission, we have to code the value-clamping ourselves. This is easily done by reading the values of the attributes and clamping the value to their defined range. Note that we have added default values for both min and max, being the lower-most and upper-most safe integer-value.
You can use for-loops like the one given below. Looks like you are operating on numbers, so I have added a + in front of x1's and y1's assignment to implicitly type-cast them to numbers.
for(var i = 1; i <= 6; i++) {
var firstRow = table.rows[i], cell = firstRow.insertCell(5);
var x1 = +table.rows[i].cells[4].getElementsByTagName('input')[0].value;
var y1 = +table.rows[i].cells[3].innerHTML;
cell.innerHTML = y1 * x1;
}

How to access HTML array object in javascript?

sorry for asking simple question. I am really a beginner in Javascript. I need to access my HTML array form object in my javascript, but I don't know how to do it.
The goal is to trigger the alert in javascript so the browser will display message according to the condition in javascript. Here is my code :
checkScore = function()
{
//I don't know how to access array in HTML Form, so I just pretend it like this :
var student = document.getElementByName('row[i][student]').value;
var math = document.getElementByName('row[i][math]').value;
var physics = document.getElementByName('row[i][physics]').value;
if (parseInt(math) >= 80 ) {
alert(student + " ,You are good at mathematic");
}
if (parseInt(physics) >= 80 ){
alert(student + " ,You are good at physics");
}
student_score.row[i][otherinfo].focus();
student_score.row[i][otherinfo].select();
}
<h2>HTML Forms</h2>
<form name="student_score" action="/action_page.php">
<table border=1>
<thead>
<td>Student</td>
<td>Math Score</td>
<td>Physics Score</td>
<td>Other info</td>
</thead>
<tbody>
<tr>
<td><input type="text" name="row[1][student]"></td>
<td><input type="number" name="row[1][math]" onblur="checkScore()" min="0" max="100"></td>
<td><input type="number" name="row[1][physics]" onblur="checkScore()" min="0" max="100"></td>
<td><input type="text" name="row[1][otherinfo]"></td>
</tr>
<tr>
<td><input type="text" name="row[2][student]"></td>
<td><input type="number" name="row[2][math]" onblur="checkScore()" min="0" max="100"></td>
<td><input type="number" name="row[2][physics]" onblur="checkScore()" min="0" max="100"></td>
<td><input type="text" name="row[2][otherinfo]"></td>
</tr>
<tr>
<td>
<input type="submit" value="Submit">
</td>
</tr>
</tbody>
</table>
</form>
<p>If you click the "Submit" button, it will save the data.</p>
We are going to leverage few things here to streamline this.
The first is Event Listeners, this removes all javascript from your HTML. It also keeps it more dynamic and easier to refactor if the table ends up having rows added to it via javascript.
Next is parentNode, which we use to find the tr that enclosed the element that was clicked;
Then we use querySelectorAll with an attribute selector to get our target fields from the tr above.
/*This does the work*/
function checkScore(event) {
//Get the element that triggered the blur
var element = event.target;
//Get our ancestor row (the parent of the parent);
var row = element.parentNode.parentNode;
//Use an attribute selector to get our infor from the row
var student = row.querySelector("[name*='[student]']").value;
var math = row.querySelector("[name*='[math]']").value;
var physics = row.querySelector("[name*='[physics]']").value;
var otherField = row.querySelector("[name*='[otherinfo]']");
if (parseInt(math, 10) >= 80) {
alert(student + " ,You are good at mathematic");
}
if (parseInt(physics, 10) >= 80) {
alert(student + " ,You are good at physics");
}
otherField.focus();
otherField.select();
}
/*Wire Up the event listener*/
var targetElements = document.querySelectorAll("input[name*='math'], input[name*='physics']");
for (var i = 0; i < targetElements.length; i++) {
targetElements[i].addEventListener("blur", checkScore);
}
<h2>HTML Forms</h2>
<form name="student_score" action="/action_page.php">
<table border=1>
<thead>
<tr>
<td>Student</td>
<td>Math Score</td>
<td>Physics Score</td>
<td>Other info</td>
</tr>
</thead>
<tbody>
<tr>
<td><input type="text" name="row[1][student]" class='student'></td>
<td><input type="number" name="row[1][math]" min="0" max="100"></td>
<td><input type="number" name="row[1][physics]" min="0" max="100"></td>
<td><input type="text" name="row[1][otherinfo]"></td>
</tr>
<tr>
<td><input type="text" name="row1[2][student]"></td>
<td><input type="number" name="row[2][math]" min="0" max="100"></td>
<td><input type="number" name="row[2][physics]" min="0" max="100"></td>
<td><input type="text" name="row[2][otherinfo]"></td>
</tr>
<tr>
<td>
<input type="submit" value="Submit">
</td>
</tr>
</tbody>
</table>
</form>
Well, it follows your line of code exactly as it is (because you said you do not want to change the code too much).
<h2>HTML Forms</h2>
<form name="student_score" action="/action_page.php">
<table border=1>
<thead>
<td>Student</td>
<td>Math Score</td>
<td>Physics Score</td>
<td>Other info</td>
</thead>
<tbody>
<tr>
<td><input type="text" name="row[1][student]"></td>
<td><input type="number" name="row[1][math]" onblur="checkScore(this)" min="0" max="100"></td>
<td><input type="number" name="row[1][physics]" onblur="checkScore(this)" min="0" max="100"></td>
<td><input type="text" name="row[1][otherinfo]"></td>
</tr>
<tr>
<td><input type="text" name="row1[2][student]"></td>
<td><input type="number" name="row[2][math]" onblur="checkScore(this)" min="0" max="100"></td>
<td><input type="number" name="row[2][physics]" onblur="checkScore(this)" min="0" max="100"></td>
<td><input type="text" name="row[2][otherinfo]"></td>
</tr>
<tr>
<td>
<input type="submit" value="Submit">
</td>
</tr>
</tbody>
</table>
</form>
JavaScript [Edited again using part of the #Jon P code, the query selector is realy more dynamic, and the value of the "other" field you requested is commented out]
//pass element to function, in html, only add [this] in parenteses
checkScore = function (element) {
//Get our ancestor row (the parent of the parent);
var row = element.parentNode.parentNode;
//Use an attribute selector to get our infor from the row
var student = row.querySelector("[name*='[student]']").value;
var math = row.querySelector("[name*='[math]']").value;
var physics = row.querySelector("[name*='[physics]']").value;
var other = row.querySelector("[name*='[otherinfo]']");
if (parseInt(math) >= 80) {
//other.value = student + " ,You are good at mathematic";
alert(student + " ,You are good at mathematic");
}
if (parseInt(physics) >= 80) {
//other.value = student + " ,You are good at physics";
alert(student + " ,You are good at physics");
}
otherField.focus();
otherField.select();
}
Tested :), and sorry about my english!
Try that, haven't tested it
var form = document.getElementsByName("student_score")[0];
var students = form.getElementsByTagName("tr");
for(var i = 0; i < students.length; i++){
var student = students[i].childnodes[0].value;
var math = students[i].childnodes[1].value;
var physics = students[i].childnodes[2].value;
if (parseInt(math) >= 80 ) {
alert(student + " ,You are good at mathematic");
}
if (parseInt(physics) >= 80 ){
alert(student + " ,You are good at physics");
}
}

How to read an array of integers from an element to get values from it?

I make a code , that randomly display an 6-item array in a div.
i want to read the array and pass it to function to calculate the mean of it?
HTML
what i must do , how can i store the data of div(id="numbers" )
and push it in array ?
<pre>
<div >
<form action="" method="post" name="meanForm" onsubmit='return false' id="formmine">
<table width="100%" border="0"
<tr>
<td colspan="3" style="background-color:#06F ;color:#FFF">Answer this problem</td>
</tr>
<tr>
<td style="color:green; font-size:20px">What is the mean of these numbers </td>
<td colspan="2" ><div id="numbers"></div>
</td>
</tr>
<tr>
<td colspan="3"> </td>
</tr>
<tr id="answerANDpic">
<td height="62" colspan="3" align="center" > <input name="" type="text" size="15" maxlength="100" height="50" style=" border: solid #0C0 ; border-width:thin" id="answer" onkeydown="searchm(this)"/> </td>
</tr>
<tr>
<td colspan="3" ><div id ="explain" ></div></td>
</tr>
<tr>
<td> </td>
<td><input name="" type="button" id="newEx" style="background-color:green ; color:white" align ="left" value="New Problem" class="send_feed" onclick="randomArray(6,0,99)" /></td>
<td><input name="" type="button" id="solution" style="background-color:#606 ; color:#FFF " align="left" class="send_feed" value="Solution" onclick="solution()"/></td>
</tr>
</table>
</form>
</div>
in JS
var myNumArray = randomArray(6,0,99);
function random_number(min,max) {
return (Math.round((max-min) * Math.random() + min));
}
function randomArray(num_elements,min,max) {
var nums = new Array;
for (var element=0; element<num_elements; element++) {
nums[element] = random_number(min,max);
}
document.getElementById("numbers").innerHTML=nums;
calcMean(nums);
}
function calcMean(nums) {
var num=0;
for (var i=0;i<nums.length;i++) {
num += parseFloat( nums[i], 6 );
}
var divide=num/nums.length;
var mean=(parseInt(divide,10));
var maxi = Math.max.apply(Math,nums);
var mini = Math.min.apply(Math,nums);
return mean,maxi,mini;
}
function searchm(ele) {
if(event.keyCode == 13) {
// alert(ele.value); // i get the value and put it on alert
var inans= ele.value;
return inans;
}
}
function soltuion(){
//read array saved in div id="numbers"
// call calcMean()
//get the mean and max min values
}
See comments in code below. Your code is not far off working.
function calcMean(nums){
var num=0;
for (var i=0;i<nums.length;i++){
// parseFloat only has one argument
// See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseFloat
num += parseFloat( nums[i])
// If the numbers in the nums array
// are already floats, you don't need parseFloat
// So maybe you can do... ?
// num += nums[i]
}
// The line below might divide by zero, so check
if (nums.length == 0) {
return 0;
}
var divide=num/nums.length;
// No need to reparse a number.
mean=divide
// This code suggests that nums is already filled with numbers
// See comment in for-loop above
var maxi = Math.max.apply(Math,nums);
var mini = Math.min.apply(Math,nums);
// This returns all 3 numbers
return [mean,mini,maxi];
// If you want just the mean,
// return mean;
}

JavaScript summing of textboxes

I could really your help! I need to sum a dynamic amount of textboxes but my JavaScript knowledge is way to week to accomplish this. Anyone could help me out? I want the function to print the sum in the p-tag named inptSum.
Here's a function and the html code:
function InputSum() {
...
}
<table id="tbl">
<tbody>
<tr>
<td align="right">
<span>June</span>
</td>
<td>
<input name="month_0" type="text" value="0" id="month_0" onchange="InputSum()" />
</td>
</tr>
<tr>
<td align="right">
<span>July</span>
</td>
<td>
<input name="month_1" type="text" value="0" id="month_1" onchange="InputSum()" />
</td>
</tr>
<tr>
<td align="right">
<span>August</span>
</td>
<td>
<input name="month_2" type="text" value="0" id="month_2" onchange="InputSum()" />
</td>
</tr>
<tr>
<td align="right">
<span>September</span>
</td>
<td>
<input name="month_3" type="text" value="0" id="month_3" onchange="InputSum()" />
</td>
</tr>
</tbody>
</table>
<p id="inputSum"></p>
function InputSum() {
var inputs = document.getElementsByTagName("input");
for (var i = 0; i < inputs.length; i++) {
if(inputs[i].id.indexOf("month_") == 0)
alert(inputs[i].value);
}
}
With a little jQuery, you could do it quite easily, using the attribute starts with selector. We then loop over them, parses their values into integers and sum them up. Something like this:
function InputSum() {
var sum = 0;
$('input[id^="month_"]').each(function () {
sum += parseInt($(this).val(), 10);
});
$("#inputSum").text(sum);
}
You could even get rid of the onchange attributes on each input if you modify the code to something like this:
$(function () {
var elms = $('input[id^="month_"]');
elms.change(function() {
var sum = 0;
elms.each(function () {
sum += parseInt($(this).val(), 10);
});
$("#inputSum").text(sum);
});
});
function InputSum() {
var month_0=document.getElementById("month_0").value;// get value from textbox
var month_1=document.getElementById("month_1").value;
var month_2=document.getElementById("month_2").value;
var month_3=document.getElementById("month_3").value;
// check number Can be omitted the
alert(month_0+month_1+month_2+month_3);//show result
}

Updating a Javascript money calculator to calculate multiple totals in real-time

I found the following money calculator on Yaldex and need assistance making some updates to it. I am resourceful enough to edit existing Javascript, but that's about it. The code is below, and a working example can be found here: http://www.yaldex.com/FSCalculators/MoneyCounter.htm
<script language="javascript" type="text/javascript">
/* Visit http://www.yaldex.com/ for full source code
and get more free JavaScript, CSS and DHTML scripts! */
<!-- Begin
function s(num, val) {
amount = num * 1; // amount is the num or NaN
sum = (!num ? 0 : num) * val; // the sum for that bill or coin
if (isNaN(amount)) { // if the entire is not a number
alert(
"' " + num + " ' is not a valid entry and that field will "
+ "not be included in the total money calculation."
);
return 0;
}
else
return sum; // if it is OK, send sum back
}
function money(form) {
hun = s(form.hun.value, 100); // Each amount is the returned value
fif = s(form.fif.value, 50); // for the amount in the s() function
twe = s(form.twe.value, 20);
ten = s(form.ten.value, 10);
fiv = s(form.fiv.value, 5);
one = s(form.one.value, 1);
hlf = s(form.hlf.value, .5);
qtr = s(form.qtr.value, .25);
dme = s(form.dme.value, .1);
nck = s(form.nck.value, .05);
pny = s(form.pny.value, .01);
// add up all the amounts
var ttl = hun + fif + twe + ten + fiv
+ one + hlf + qtr + dme + nck + pny;
// rounds total to two decimal places
ttl = "" + ((Math.round(ttl * 100)) / 100);
dec1 = ttl.substring(ttl.length-3, ttl.length-2);
dec2 = ttl.substring(ttl.length-2, ttl.length-1);
if (dec1 != '.') { // adds trailing zeroes if necessary
if (dec2 == '.') ttl += "0";
else ttl += ".00";
}
form.total.value = "$ " + ttl; // display total amount
}
// End -->
</script>
<form name=coinform>
<table border=1>
<tr>
<td align=center>$ 100</td>
<td align=center>$ 50</td>
<td align=center>$ 20</td>
<td align=center>$ 10</td>
<td align=center>$ 5</td>
<td align=center>$ 1</td>
</tr>
<tr>
<td align=center><input type=text name=hun size=3></td>
<td align=center><input type=text name=fif size=3></td>
<td align=center><input type=text name=twe size=3></td>
<td align=center><input type=text name=ten size=3></td>
<td align=center><input type=text name=fiv size=3></td>
<td align=center><input type=text name=one size=3></td>
</tr>
<tr>
<td colspan=6> </td>
</tr>
<tr>
<td> </td>
<td align=center>50 ¢</td>
<td align=center>25 ¢</td>
<td align=center>10 ¢</td>
<td align=center>5 ¢</td>
<td align=center>1 ¢</td>
</tr>
<tr>
<td> </td>
<td align=center><input type=text name=hlf size=3></td>
<td align=center><input type=text name=qtr size=3></td>
<td align=center><input type=text name=dme size=3></td>
<td align=center><input type=text name=nck size=3></td>
<td align=center><input type=text name=pny size=3></td>
</tr>
<tr>
<td colspan=5 align=center>
<input type=button name=calc value="Calculate" onClick="javascript:money(this.form)">
<input type=text name=total size=10>
</td>
</tr>
</table>
</form>
I have already determined how to update the grand total in real-time by adding an onkeyup event to each input field, but I would also like to add an additional field to each dollar/coin amount that would display the total amount for each unit when the user enters each quantity, AND update the grand total for all amounts, both in real-time. I would also like to be able to display the grand total as two amounts, in both total dollars and total cents (e.g. $100.00 / 10000 cents). I envision it looking more or less like this:
$100 x ___ = $___ total
$50 x ___ = $___ total
.
.
.
5¢ x ___ = $___ total
1¢ x ___ = $___ total
GRAND TOTAL $_______ / _______ cents
Any and all guidance and assistance would be appreciated. Thank you!
Knockout JS would be a good way to implement something like this. Here is a quick example of what can be done. The quantity for each dollar amount would be an observable and the totals would be computed observables:
HTML
<input type="text" data-bind="value: hundredsQuantity, valueUpdate: 'afterkeydown'" />
<span id="hundredsResult" data-bind="text: hundredsAmount"></span>
View Model (JS)
return function myViewModel() {
var self = this;
self.hundredsQuantity = ko.observable();
self.hundredsAmount = ko.computed(function () {
return parseInt(self.hundredsQuantity) * 100;
});
};
In this case the data binding is configured to update as soon as the user begins typing a character (afterkeyDown).
The view model would then be created by var vm = new myViewModel(); and the bindings applied by ko.applyBindings(vm). The documentation on the Knockout site is very good and will provide more explanation of the pattern shown here. Good luck!

Categories

Resources