I'm working on creating a page in which someone could calculate their Net Worth by entering various values. The input text will show a .00 afterwards if no decimal point is added in. I'm having troubles in getting a sum of all of the values.
Java:
<script type="text/javascript"><!--
function updatesum() {
document.form.TotalAssets.value = (document.form.CashOnHand.value -0) + (document.form.CashInChecking.value -0);
}
//-->
</script>
HTML:
<input type="text" onblur="if(this.value.indexOf('.')==-1)this.value=this.value+'.00'" onchange="format(this); updatesum()" onkeyup="format(this)" maxlength="11" value="0" name="CashOnHand" /></td>
</tr>
<tr>
<td><strong>Cash in Checking</strong></td>
<td>$
<input type="text"
onblur="if(this.value.indexOf('.')==-1)this.value=this.value+'.00'" onchange="format(this); updatesum()" onkeyup="format(this)" maxlength="11" value="0" name="CashInChecking" /></td>
</tr>
<tr>
<td align="right"><strong>Total Assets</strong></td>
<td>$<input name="TotalAssets" readonly ></td>
</tr>
It's not giving me a sum of the the values that I'm adding.
I think this is because document.form is undefined, but this one works:
function updatesum() {
var hand = parseFloat(document.forms[0].CashOnHand.value);
var checking = parseFloat(document.forms[0].CashInChecking.value);
document.forms[0].TotalAssets.value = hand - checking;
}
Related
I have a page like this:
[http://jsfiddle.net/ph75fggo/]
[http://jsfiddle.net/ph75fggo/5/]//more reliable sample
And I tried to make a simple cashier apps, with help of JavaScript make an auto count on both rows and columns.
This is the result I want to get:
http://jsfiddle.net/wrz8bc10/
My Final Trying: jsfiddle.net
Your Question is not drawing the clear picture of your requirement. As far as I understand, you need to have a gross amount after deducting the discount for each row and the total discounted and net amounts at the end.
First thing that you should do is to assign a common class to each of the child of every tr. It makes your JS code a lot simpler. Otherwise you need write some extra LOC to select specific element.
<tr>
<td><input type='text' class="amount" id='harga2' value='250000' /></td>
<td><input type='text' class="discount" id='diskon2' value='' /></td>
<td><input type='text' class="grossAmount" id='total2' value='' /></td>
</tr>
<tr>
<td><input type='text' class="amount" id='harga2' value='250000' /></td>
<td><input type='text' class="discount" id='diskon2' value='' /></td>
<td><input type='text' class="grossAmount" id='total2' value='' /></td>
</tr>
<tr>
<td><input type='text' class="amount" id='harga2' value='250000' /></td>
<td><input type='text' class="discount" id='diskon2' value='' /></td>
<td><input type='text' class="grossAmount" id='total2' value='' /></td>
</tr>
After that you can use the following function:
function myFunction(){
var amounts = document.getElementsByClassName("amount");
var discounts = document.getElementsByClassName("discount");
var gAmounts = document.getElementsByClassName("grossAmount");
var lv,rowSum,totDis=0,totAmount=0;
for(lv=0;lv>gAmounts.length;lv++){
rowSum += (parseInt(amounts[lv].value)-parseInt(discounts[lv].value));
totAmount += rowSum;
totDis += parseInt(discounts[lv].value);
gAmounts[lv].value = totAmount;
}
}
But if you don't want change your HTML, Then you can use the following code:
function myFunc(){
var lv,rowSum,totDis=0,totAmount=0;
var TRs = document.getElementsByTagName("table")[0].childNodes; //assuming that the table is the first one on your page.
var lv;
for(lv=1;lv<tab.length;lv++){ // starting the counter with 1 as the first child of the table contains headings
rowSum += (parseInt(TRs[lv][0].value)-parseInt(TRs[lv][1].value));
totAmount += rowSum;
totDis += parseInt(TRs[lv][1].value);
TRs[lv].value = rowSum;
}
}
You were getting the elements with ids 'id1' and 'id2' whereas there are no such elements present in your html with those ids, they should be 'harga1' and 'diskon1'. Also, when you write your JS in a function, make sure to call it at the end, but you don't need to write it in a function in this specific case, so here is your solution:
var rows = document.getElementById("myTable").getElementsByTagName("tr").length;
for(var i=1; i<rows; i++){
var harga = parseInt(document.getElementById('harga'+i).value);
var diskon = parseInt(document.getElementById('diskon'+i).value);
var total = harga - diskon;
document.getElementById('total'+i).value = total;
}
Get the number of rows, then keep getting the harga and diskon values one by one.. harga1, harga2, harga3.. ('harga'+i) subtract their values and put them in total1, total2 and total 3.. this will work if you add more rows as well..
See the DEMO here
I have updated the JSFiddle here:
[http://jsfiddle.net/ph75fggo/4/]
This is just one approach at what you are trying to do, where I changed your code as little as possible, and still uses hard coded variable names (instead of the above answer that automatically iterates over all rows). You can use my answer to help simply extend your cashier application.
do you mean like this link?
you can change use the parameters if you want
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<table>
<tr>
<td>Total Harga</td>
<td>Total Diskon</td>
<td>Total Bayar</td>
</tr>
<tr>
<td><input type='text' id='harga1' onchange="dynamic()" value='250000' /></td>
<td><input type='text' id='diskon1' value='50' /></td>
<td><input type='text' id='total1' value='' /></td>
</tr>
<tr>
<td><input type='text' id='harga2' value='250000' /></td>
<td><input type='text' id='diskon2' value='0' /></td>
<td><input type='text' id='total2' value='0' /></td>
</tr>
<tr>
<td><input type='text' id='harga3' value='250000' /></td>
<td><input type='text' id='diskon3' value='0' /></td>
<td><input type='text' id='total3' value='0' /></td>
</tr>
</table>
</body>
<script>
function dynamic(){
var harga1 = document.getElementById('harga1').value;
var diskon1 = document.getElementById('diskon1').value/100;
var totalharga = harga1 - (harga1 * diskon1);
document.getElementById("total1").value = totalharga;
}
</script>
</html>
I have the table:
<table id="form_Dependentes" width="100%" cellpadding="0" cellspacing="0" class="form">
<tr>
<th colspan="4" valign="middle" scope="col">Dependentes</th>
</tr>
<tr>
<td colspan="2"><label>Nome</label><input type="text" name="depNome_01" maxlength="128" /></td>
<td width="20%"><label>Parentesco</label><input type="text" name="depParentesco_01" maxlength="16" /></td>
<td width="20%"><label>Data Nasc.</label><input type="text" name="depDataNasc_01" maxlength="10" /></td>
</tr>
<tr>
<td colspan="2"><label>Nome</label><input type="text" name="depNome_02" maxlength="128" /></td>
<td width="20%"><label>Parentesco</label><input type="text" name="depParentesco_02" maxlength="16" /></td>
<td width="20%"><label>Data Nasc.</label><input type="text" name="depDataNasc_02" maxlength="10" /></td>
</tr>
... etc.
</table>
This table is formatted to be printed and used online. Online, I wish to put buttons to add and remove those lines with input tags above the header. Is not complicate to format the html, but I was thinking about removing and adding tr lines using xml javascript capabilities, but don't know exactly how...
Edit: I don't get what so wrong with this question that is getting negative. Whatever... I'm working in this code:
var cadFormTableRow;
var cadFormTable;
function cadFormAtivar(){
document.getElementById("form_FotoUpload").innerHTML = 'Foto (máximo 1MB): <input name="foto" type="file" accept="image/*;capture=camera">';
document.getElementById("form_Assinatura").innerHTML = '';
document.getElementById("form_Dados").innerHTML = 'Dependentes: <button type="button" onclick="cadFormDep(1);"> + </button> <button type="button" onclick="cadFormDep(-1);"> - </button><br /><button type="button" onclick="cadFormTestar();">Enviar</button>';
cadFormTable = document.getElementById("form_Dependentes");
var nr = cadFormTable.rows.length;
cadFormTableRow = cadFormTable.rows[1];
console.log("Rows: "+nr);
//console.log("Row: "+cadFormTableRow.outerHTML);
for(i=0; i<nr-1; i++){
cadFormTable.deleteRow(1);
}
}
function cadFormDep(a){
if(a>0){
cadFormTable.appendChild(cadFormTableRow);
} else {
var nr = cadFormTable.rows.length;
cadFormTable.deleteRow(nr-1);
}
}
The problem seams to be appendChild is not good, I should go deep in HTMLTableElement, I guess, that's what I like to choose the better approach first... If I could make it work, I'll answer myself, I don't mind you don't like it, it's a free world, right?
It seams HTMLTableElement is the best approach for inserting and deleting rows. HTMLTableElement.insertRow creates a row linked with the original object. Here is the same code with HTMLTableElement corrections needed:
var cadFormTableRow;
var cadFormTable;
function cadFormAtivar(){
document.getElementById("form_FotoUpload").innerHTML = 'Foto (máximo 1MB): <input name="foto" type="file" accept="image/*;capture=camera">';
document.getElementById("form_Assinatura").innerHTML = '';
document.getElementById("form_Dados").innerHTML = 'Dependentes: <button type="button" onclick="cadFormDep(1);"> + </button> <button type="button" onclick="cadFormDep(-1);"> - </button><br /><button type="button" onclick="cadFormTestar();">Enviar</button>';
cadFormTable = document.getElementById("form_Dependentes");
var nr = cadFormTable.rows.length;
cadFormTableRow = cadFormTable.rows[1];
for(i=0; i<nr-1; i++){
cadFormTable.deleteRow(1);
}
}
function cadFormDep(a){
if(a>0){
var row = cadFormTable.insertRow(-1);
var html = cadFormTableRow.innerHTML.replace(/{n}/g, String(cadFormTable.rows.length-1));
row.innerHTML = html;
console.log("Row: "+html);
} else {
var nr = cadFormTable.rows.length;
cadFormTable.deleteRow(nr-1);
}
}
I think working with the cells and inputs as string were easier in this case - I'd pick a sample (as below) and add a number replacing {n} by a numbering:
<tr>
<td colspan="2"><label>Nome</label><input type="text" name="depNome_{n}" maxlength="128" /></td>
<td width="20%"><label>Parentesco</label><input type="text" name="depParentesco_{n}" maxlength="16" /></td>
<td width="20%"><label>Data Nasc.</label><input type="text" name="depDataNasc_{n}" maxlength="10" /></td>
</tr>
This way, every the information will have an unique name.
Here are my text fields
<tr>
<td>Price:</td>
<td><input type="text" name="price" id="form_textfield" class="price" autocomplete="off" /></td>
</tr>
<tr>
<td>Liters:</td>
<td><input type="text" name="liters" id="form_textfield" class="liters" autocomplete="off" /></td>
</tr>
<tr>
<td>Amount:</td>
<td><input type="text" name="jqueryamount" id="form_textfield" class="jqueryamount" autocomplete="off" /></td>
</tr>
Currently when you input price and liters, it multiplies them and outputs the answer to jqueryamount textfield it works well. What i want to do is when i type in the amount and the price it will divide the jqueryamount field with the price field and output it to liters field.
UPDATE FIXED
// JavaScript Document
$(document).ready(function(){
$('.price').keyup(calculate);
$('.liters').keyup(calculate);
});
function calculate(e)
{
$('.jqueryamount').val($('.price').val() * $('.liters').val());
}
// JavaScript Document
$(document).ready(function(){
$('.jqueryamount').keyup(calculate1);
$('.price').keyup(calculate1);
});
function calculate1(e)
{
$('.liters').val($('.jqueryamount').val() / $('.price').val());
}
JUST ADDED A NEW NAME FOR THE DIVIDE FUNCTION... silly me thanks for the help guys
Here are my javascript
// JavaScript Document
$(document).ready(function(){
$('.price').keyup(calculate);
$('.liters').keyup(calculate);
});
function calculate(e)
{
$('.jqueryamount').val($('.price').val() * $('.liters').val());
}
// JavaScript Document
$(document).ready(function(){
$('.jqueryamount').keyup(calculate);
$('.price').keyup(calculate);
});
function calculate(e)
{
$('.liters').val($('.jqueryamount').val() / $('.price').val());
}
My problem is when adding the divide function the multiplication part will no longer work, i can no longer type inside the liters textfield it gives me NaN error.
Use parseFloat() function after the get the value from input, which converts string to number.
When you put the value price and amount the liters would show like this.
$('.price').keyup(calculateLiters, calculateAmount);
$('.jqueryamount').keyup(calculateLiters);
$('.liters').keyup(calculateAmount);
function calculateLiters(e) {
price = parseFloat($('.price').val());
amount = parseFloat($('.jqueryamount').val());
if(!isNaN(price) && !isNaN(amount)){
$('.liters').val(amount / price);
}
}
function calculateAmount(e) {
price = parseFloat($('.price').val());
liters = parseFloat($('.liters').val());
if(!isNaN(price) && !isNaN(liters)){
$('.jqueryamount').val(price * liters);
}
}
Demo
I swapped some class names and id's to make code more efficient.
HTML
<tr>
<td>Price:</td>
<td><input type="text" name="price" id="price" class="form_textfield" autocomplete="off" /></td>
</tr>
<tr>
<td>Liters:</td>
<td><input type="text" name="liters" id="liters" class="form_textfield" autocomplete="off" /></td>
</tr>
<tr>
<td>Amount:</td>
<td><input type="text" name="jqueryamount" id="jqueryamount" class="form_textfield" autocomplete="off" /></td>
</tr>
Javascript
// JavaScript Document
$(document).ready(function(){
$('.form_textfield').keyup(calculate);
});
function calculate()
{
$('#jqueryamount').val($('#price').val() * $('#liters').val());
$('#liters').val($('#jqueryamount').val() / $('#price').val());
}
Here is a working demo. http://jsfiddle.net/vnaDK/
Trying to pull information from my form input fields and calculate them using JavaScript. It does not seem to be working.
HTML (default1.html)
<script type="text/javascript" src="multiplication.js" language="javascript"></script>
<form>
<table>
<tr><!--Row 2-->
<td class="tdSize7">
<input class="input" name="name1" type="text"/>
</td>
<td class="tdSize7">
<input class="input" name="source1" type="text"/>
</td>
<td class="tdSize8">
<p>$</p>
</td>
<td class="tdSize9">
<input class="input" name="income1" type="text"/>
</td>
<td class="tdSize8">
<p>X12</p>
</td>
<td class="tdSize8">
<p>$</p>
</td>
<td class="tdSize9">
<input name="ann1" disabled="disabled"/>
</td>
</tr>
<td class="tdSize9"><input class="inputSize2" name="" type="button" value="Calculate" onclick="addme(this.form)"/></td>
</table>
</form>
JavaScript (multiplication.js)
function addme(form) {
//Constant Variables
const twelve = Number (12);
const fourHun = Number (400);
const fourHunEighty = Number (480);
//Monthly Income 1
var income1 = Number(frm.income1.value);
var val = income1 * twelve;
frm.ann1.value = val;
}
My JavaScript will not calculate and input my results back into my form.
This is just a sample of my code. I am hoping this will tell you enough and help you, in helping me fixing my problem.
Did you intend to use form instead of frm? That is part of your problem
Try:
var income1 = Number(form.income1.value);
var val = income1 * twelve;
form.ann1.value = val;
Or change
function addme(form)
to
function addme(frm)
I have a table including input text fields with the basic structure below. I am having trouble building a function to iterate all rows in the table and sum all the values of input fields beginning with BFObel where the value of the field beginning with BFOkto are the same. So for the basic example below the sum for value 1111 would be 2000 and the sum for value 1112 would be 3000. Each sum would then be written to an inputfield with the id field1111, field1112 etc...
<table>
<tr id="BFOrow1">
<td><input type="text" id="BFOtxt1" value="text"/></td>
<td><input type="text" id="BFOkto1" value="1111" /></td>
<td><input type="text" id="BFObel1" value="1000" /></td>
</tr>
<tr id="BFOrow2">
<td><input type="text" id="BFOtxt2" value="text"/></td>
<td><input type="text" id="BFOkto2" value="1111" /></td>
<td><input type="text" id="BFObel2" value="1000" /></td>
</tr>
<tr id="BFOrow3">
<td><input type="text" id="BFOtxt3" value="text"/></td>
<td><input type="text" id="BFOkto3" value="1112" /></td>
<td><input type="text" id="BFObel3" value="1000" /></td>
</tr>
<tr id="BFOrow4">
<td><input type="text" id="BFOtxt4" value="text"/></td>
<td><input type="text" id="BFOkto4" value="1112" /></td>
<td><input type="text" id="BFObel4" value="1000" /></td>
</tr>
<tr id="BFOrow5">
<td><input type="text" id="BFOtxt5" value="text"/></td>
<td><input type="text" id="BFOkto5" value="1112" /></td>
<td><input type="text" id="BFObel5" value="1000" /></td>
</tr>
</table>
You'll want to use an object literal to track your results and an "attribute starts with" selector to find the text inputs:
var accumulator = { };
$('table input[id^=BFOkto]').each(function() {
var sum_id = this.id.replace(/^BFOkto/, 'BFObel');
if(!accumulator[this.value])
accumulator[this.value] = 0;
accumulator[this.value] += parseInt($('#' + sum_id).val(), 10);
});
// accumulator now has your results.
Don't forget the second argument to parseInt() so that you don't get tripped up by values with leading zeros (which look like octal without a specified radix).
For example: http://jsfiddle.net/ambiguous/QAqsQ/ (you'll need to run this in a browser with an open JavaScript console to see the resulting accumulator).
var sum1111 = 0;
$('input[value="1111"]').each(function() {
var ordinal = $(this).attr('id').replace('BFOkto', '');
sum1111 += parseInt($('#BFObel' + ordinal).val());
});
At the end, sum1111 should equal 2000.
For reuse, wrap the logic in a function:
function getSum(BFOkto) {
var sum = 0;
var ordinal = null;
$('input[value="' + BFOkto + '"]').each(function() {
ordinal = $(this).attr('id').replace('BFOkto', '');
sum += parseInt($('#BFObel' + ordinal).val());
});
return sum;
}
And then call:
getSum('1111');
getSum('1112');
A different approach: find all input fields with prefix BFOkto, for each, find the input with prefix BFObel sharing same parent and accumulate its value
ref = $("table td input[id^=BFOkto]");
var sums = new Object();
ref.each(function(){
val = parseInt($(this).closest('tr').find("td input[id^=BFObel]").val(), 10);
property = 'i'+ this.value;
sums[property] = (sums[property] || 0 ) + val;
});
alert(sums['i1111']);
alert(sums['i1112']);
sums will be an object with properties
i1111 = 2000
i1112 = 3000
Despite javascript allows it, it is better not to use pure numeric properties for objects (associative arrays), hence the i prefix
The running example is here:
http://jsfiddle.net/TbSau/1/