I am trying to multiply the user input on input field "full_day" by the "var fullprice", and display the result in readonly input field "total_full" what am i doing wrong that is causing it not to work?
<div id="wrapper">
<div id="header"></div>
<table width="899" border="1" align="left" cellpadding="1">
<form action="" method="get" name="myform">
<tr>
<td width="275"><label>Company Name</label></td>
<td width="180"><input type="text" name="companyname" id="companyname" /></td>
<td width="27"> </td>
<td width="223">Enquiry Date</td>
<td width="160"><input type="text" name="enquiry_date" id="enquiry_date" class="datepicker" /></td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td>Conference Date In</td>
<td><input type="text" name="conference_date_in" id="conference_date_in" class="datepicker" /></td>
<td> </td>
<td>Conference Date Out</td>
<td><input type="text" name="conference_date_out" id="conference_date_out" class="datepicker" /></td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td>Number of Delegates</td>
<td><input type="text" name="no_of_delegates" id="no_of_delegates" /></td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td>Accommodation:</td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td><p>Check in Date</p></td>
<td><input type="text" name="check_in_date" id="check_in_date" class="datepicker" /></td>
<td><p> </p></td>
<td><p>Check out Date</p></td>
<td><p>
<input type="text" name="check_out_date" id="check_out_date" class="datepicker" />
</p></td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td>Total Days Accommodation</td>
<td><input type="text" name="total_days_acc" id="total_days_acc" /></td>
</tr>
<tr>
<td>Number of Rooms:</td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td>Single</td>
<td><input type="text" name="no_of_rooms_single" id="no_of_rooms_single" /></td>
<td> </td>
<td>Double / Twin</td>
<td><input type="text" name="no_of_rooms_double" id="no_of_rooms_double" /></td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td>Contact Person</td>
<td><input type="text" name="contact_person" id="contact_person" /></td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td>Telephone Number</td>
<td><input type="text" name="tel_no" id="tel_no" /></td>
<td> </td>
<td>Fax Number</td>
<td><input type="text" name="fax_no" id="fax_no" /></td>
</tr>
<tr>
<td>Cell Number</td>
<td><input type="text" name="cell_no" id="cell_no" /></td>
<td> </td>
<td>Email</td>
<td><input type="text" name="email" id="email" /></td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td>Full Day Conference # R260.00 p/p</td>
<td><input type="text" name="full_day" id="full_day" /></td>
<td> </td>
<td>Total Full Day</td>
<td><input type="text" name="total_full" id="total_full" readonly="readonly" /></td>
</tr>
<tr>
<td>Half Day Conference # R240.00 p/p</td>
<td><input type="text" name="half_day" id="half_day" /></td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td>Single Rooms # R480.00 p/p</td>
<td><input type="text" name="single_rooms" id="single_rooms" /></td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td>Double / Twin Rooms # R720.00 p/p</td>
<td><input type="text" name="double_rooms" id="double_rooms" /></td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td>Data Projector # R400.00 rental p/day</td>
<td><input type="text" name="data_proj" id="data_proj" /></td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td>Sub Total</td>
<td><input type="text" name="sub_total" id="sub_total" /></td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
</form>
</table>
</div>
</body>
</html>
<script type="text/javascript">
$(function() {
$(".datepicker").datepicker({ minDate: -0, maxDate: "+100M +10D",dateFormat: 'dd-mm-yy'})
({
changeMonth: true,
changeYear: true,
});
});
var enquiry_date = $.datepicker.formatDate('dd-mm-yy', new Date());
document.getElementById('enquiry_date').value = enquiry_date;
var calcDate = function() {
var start = $('#conference_date_in').datepicker('getDate');
var end = $('#conference_date_out').datepicker('getDate');
var days = (end - start) / 1000 / 60 / 60 / 24;
if(days==0) days=1
if( days >= 0 ) {
document.getElementById('total_days').value = days;
}
}
$('#conference_date_out').change(calcDate);
$('#conference_date_in').change(calcDate);
var calcDateAcc = function() {
var startacc = $('#check_in_date').datepicker('getDate');
var endacc = $('#check_out_date').datepicker('getDate');
var daysacc = (endacc - startacc) / 1000 / 60 / 60 / 24;
if(daysacc==0) daysacc=1
if( daysacc >= 0 ) {
document.getElementById('total_days_acc').value = daysacc;
}
}
$('#check_in_date').change(calcDateAcc);
$('#check_out_date').change(calcDateAcc);
function calculateFull()
{
var fulldays = document.getElementById("full_day").value;
var fullprice = 260;
var result = fulldays * fullprice;
document.getElementById("total_full").innerHTML = result;
}
$('#full_day').change(calculateFull);
</script>
total_full is input box, so you should set value instead of innetHTML
document.getElementById("total_full").innerHTML = result;
document.getElementById("total_full").value = result;
document.getElementByid("full_day").value returns a string. You have to convert this string into a number before multiplying it with fullprice
var fulldays = parseInt(document.getElementById("full_day").value, 10);
And change document.getElementById("total_full").innerHTML = result;
to document.getElementById("total_full").value = result;
Related
I'm trying to achieve two additions in my code.
I am trying to get the sum of the row values in the last column of the row
I am trying to get the sum of all the final columns in another div
I've achieved the first, my code gives me the correct value of each row. However the second sum is not populating the addition. It's giving me the same value of each row, but I want the value of all rows.
$('.bonus-sum').keyup(function() {
var sum = 0;
var salary = parseFloat($(this).closest('tr').find('.wagein').text());
var bonus = parseFloat($(this).closest('tr').find('.bonus-sum').val()) || 0;
$(this).closest('tr').find('.bonus-in:checked').each(function() {
sum = salary + bonus;
});
$(this).closest('tr').find('.netpay').text(sum.toFixed(2));
var netpay = 0;
netpay += sum;
$('#total').text('₹ ' + netpay.toFixed(2));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<table>
<thead>
<tr>
<th class="text-center"><input type="checkbox" checked="checked" class="checkAll" name="checkAll" /></th>
<th>#</th>
<th>Beneficiary Name</th>
<th class="text-right box">Bonus ₹</th>
<th class="text-right">Salary ₹</th>
<th class="text-right">Net pay ₹</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<input type="checkbox" id="bene_id" checked="checked" class="bonus-in" name="bene_id[]" value="" />
</td>
<td>1</td>
<td>Chellammal Kochimoni</td>
<td><input type="text" id="bonus_temp" class="bonus-sum" name="bonus_temp[]" value="" /></td>
<td class="wagein">400</td>
<td class="netpay"></td>
</tr>
<tr>
<td>
<input type="checkbox" id="bene_id" checked="checked" class="bonus-in" name="bene_id[]" value="" />
</td>
<td>2</td>
<td>Christal Prema G.</td>
<td><input type="text" id="bonus_temp" class="bonus-sum" name="bonus_temp[]" value="" /></td>
<td class="wagein">400</td>
<td class="netpay"></td>
</tr>
<tr>
<td>
<input type="checkbox" id="bene_id" checked="checked" class="bonus-in" name="bene_id[]" value="" />
</td>
<td>3</td>
<td>Kamalesan T.</td>
<td><input type="text" id="bonus_temp" class="bonus-sum" name="bonus_temp[]" value="" /></td>
<td class="wagein">400</td>
<td class="netpay"></td>
</tr>
<tr>
<td>
<input type="checkbox" id="bene_id" checked="checked" class="bonus-in" name="bene_id[]" value="" />
</td>
<td>4</td>
<td>Palammal A.</td>
<td><input type="text" id="bonus_temp" class="bonus-sum" name="bonus_temp[]" value="" /></td>
<td class="wagein">400</td>
<td class="netpay"></td>
</tr>
<tr>
<td>
<input type="checkbox" id="bene_id" checked="checked" class="bonus-in" name="bene_id[]" value="" />
</td>
<td>4</td>
<td>Thangapazham</td>
<td><input type="text" id="bonus_temp" class="bonus-sum" name="bonus_temp[]" value="" /></td>
<td class="wagein">400</td>
<td class="netpay"></td>
</tr>
</tbody>
</table>
</div>
<div>Total Net Pay <span id="total">₹ 0.00</span></div>
To fix this you need to create a loop which iterates through all the .netpay elements, not just the one which was updated, and generates the total value.
In addition, you need to perform the same action when the checkbox is changed. The logic itself can also be made more succinct and DRY, like this:
$('.bonus-sum').on('input', updateRowTotal);
$('.bonus-in').on('change', updateRowTotal).trigger('change'); // trigger is to set values on load
function updateRowTotal() {
let $tr = $(this).closest('tr');
let salary = parseFloat($tr.find('.wagein').text()) || 0;
let bonus = parseFloat($tr.find('.bonus-sum').val()) || 0
let rowTotal = salary + ($tr.find('.bonus-in:checked').length ? bonus : 0);
$tr.find('.netpay').text(rowTotal.toFixed(2));
updateTotal();
}
function updateTotal() {
let total = 0;
$('.netpay').each((i, el) => total += parseFloat(el.textContent.trim() || 0));
$('#total').text('₹ ' + total.toFixed(2));
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<table>
<thead>
<tr>
<th class="text-center"><input type="checkbox" checked="checked" class="checkAll" name="checkAll" /></th>
<th>#</th>
<th>Beneficiary Name</th>
<th class="text-right box">Bonus ₹</th>
<th class="text-right">Salary ₹</th>
<th class="text-right">Net pay ₹</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<input type="checkbox" checked="checked" class="bonus-in" name="bene_id[]" value="" />
</td>
<td>1</td>
<td>Chellammal Kochimoni</td>
<td><input type="text" class="bonus-sum" name="bonus_temp[]" value="" /></td>
<td class="wagein">400</td>
<td class="netpay"></td>
</tr>
<tr>
<td>
<input type="checkbox" checked="checked" class="bonus-in" name="bene_id[]" value="" />
</td>
<td>2</td>
<td>Christal Prema G.</td>
<td><input type="text" class="bonus-sum" name="bonus_temp[]" value="" /></td>
<td class="wagein">400</td>
<td class="netpay"></td>
</tr>
<tr>
<td>
<input type="checkbox" checked="checked" class="bonus-in" name="bene_id[]" value="" />
</td>
<td>3</td>
<td>Kamalesan T.</td>
<td><input type="text" class="bonus-sum" name="bonus_temp[]" value="" /></td>
<td class="wagein">400</td>
<td class="netpay"></td>
</tr>
<tr>
<td>
<input type="checkbox" checked="checked" class="bonus-in" name="bene_id[]" value="" />
</td>
<td>4</td>
<td>Palammal A.</td>
<td><input type="text" class="bonus-sum" name="bonus_temp[]" value="" /></td>
<td class="wagein">400</td>
<td class="netpay"></td>
</tr>
<tr>
<td>
<input type="checkbox" checked="checked" class="bonus-in" name="bene_id[]" value="" />
</td>
<td>4</td>
<td>Thangapazham</td>
<td><input type="text" class="bonus-sum" name="bonus_temp[]" value="" /></td>
<td class="wagein">400</td>
<td class="netpay"></td>
</tr>
</tbody>
</table>
</div>
<div>Total Net Pay <span id="total">₹ 0.00</span></div>
Note the removal of all the duplicate id attributes in your HTML . They are invalid, and are not required anyway.
I have introduced new variable totalsum.
Replace the below function .your code will work as expected
<script>
var totalsum=0;
$('.bonus-sum').keyup(function() {
var sum = 0;
var salary = parseFloat($(this).closest('tr').find('.wagein').text());
var bonus = parseFloat($(this).closest('tr').find('.bonus-sum').val()) || 0;
$(this).closest('tr').find('.bonus-in:checked').each(function() {
sum = salary + bonus;
totalsum+=sum;
});
$(this).closest('tr').find('.netpay').text(sum.toFixed(2));
var netpay = 0;
netpay += totalsum;
$('#total').text('₹ ' + netpay.toFixed(2));
});
</script>
I have a spreadsheet of data and input fields.
When the input field is empty, it should click the copy text button from the row with class "shipdate". I always copy the entry in the code. Can anyone tell me where I'm wrong.
This is my code
$(".btn-yes").click(function() {
var $val = $(document).find('.date');
$('.date').each(function() {
var $val = $(this).val();
if ($val === "") {
$('tr').each(function() {
var $this = $(this),
daata = $this.find('td.shipdate').html();
$this.find('input').val(anData);
})
} else(
console.log("empty")
)
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<table>
<thead>
<tr>
<th>Example1</th>
<th>Example2</th>
<th>Example3</th>
<th>Example4</th>
</tr>
</thead>
<tbody>
<tr>
<td> text1</td>
<td> text2 </td>
<td> <input type="text" value="" class="date" /> </td>
<td class="shipdate"> 31.10.2019.</td>
</tr>
<tr>
<td> text1</td>
<td> text2 </td>
<td> <input type="text" value="" class="date" /> </td>
<td class="shipdate"> 31.10.2019.</td>
</tr>
<tr>
<td> text1</td>
<td> text2 </td>
<td> <input type="text" value="" class="date" /> </td>
<td class="shipdate"> 31.10.2019.</td>
</tr>
<tr>
<td> text1</td>
<td> text2 </td>
<td> <input type="text" value="" class="date" /> </td>
<td class="shipdate"> 31.10.2019.</td>
</tr>
</tbody>
</table>
<div>
<button class="btn-yes">
Click here
</button>
</div>
</div>
You likely meant this. Note I had to trim and remove the trailing dot in the shipdate
You can remove the .slice(0,-1) if the shipdate cell contains a date without a trailing dot
You can also freely change $(this).parent().next().text() to $(this).closest("tr").find(".shipdate").text()
in case you want to move the cells around
$(".btn-yes").click(function() {
$('.date').each(function() {
var $val = $(this).val();
var shipdate = $.trim($(this).parent().next().text()).slice(0,-1)
$(this).val($val === "" ? shipdate : $val)
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<table>
<thead>
<tr>
<th>Example1</th>
<th>Example2</th>
<th>Example3</th>
<th>Example4</th>
</tr>
</thead>
<tbody>
<tr>
<td> text1</td>
<td> text2 </td>
<td> <input type="text" value="" class="date" /> </td>
<td class="shipdate"> 31.10.2019.</td>
</tr>
<tr>
<td> text1</td>
<td> text2 </td>
<td> <input type="text" value="" class="date" /> </td>
<td class="shipdate"> 31.10.2019.</td>
</tr>
<tr>
<td> text1</td>
<td> text2 </td>
<td> <input type="text" value="" class="date" /> </td>
<td class="shipdate"> 31.10.2019.</td>
</tr>
<tr>
<td> text1</td>
<td> text2 </td>
<td> <input type="text" value="" class="date" /> </td>
<td class="shipdate"> 31.10.2019.</td>
</tr>
</tbody>
</table>
<div>
<button class="btn-yes">
Click here
</button>
</div>
</div>
Hello and thank you in advance.
I have a table where some values prefilled (like 111.36) but when I try to do math with the numbers, or even display the number nothing happens.
Thank you for your assistance,
Marc (new at Javascript)
function calculate_it() {
window.alert("In function calculate_it");
var x = document.getElementByID("Numb01").value;
window.alert(x);
} //end function
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<TITLE>Javascript Table</TITLE>
<link href="style.css" type="text/css" rel="stylesheet">
</head>
<body>
<h3>A demonstration of calculators</h3>
<table id="t01">
<caption>Chek this out!</caption>
<tr>
<th>Date</th>
<th>Number 1</th>
<th>Number 2</th>
<th>Number 3</th>
<th>Number 4</th>
</tr>
<tr>
<td>
<input type="text" id="Date01" value="WED21DEC16" size="10" />
</td>
<td>
<input type="number" id="Numb01" value=111.36 size="5" />
</td>
<td>
<input type="number" id="Numb02" value=222.36 size="5" />
</td>
<td>
<input type="number" id="Numb03" value=333.36 size="5" />
</td>
<td>
<input type="number" id="Numb04" value=444.36 size="5" />
</td>
</tr>
<tr>
<td>
<input type="text" id="Date02" value="WED22DEC16" size="10" />
</td>
<td>
<input type="number" id="Numb05" value=555.36 size="5" />
</td>
<td>
<input type="number" id="Numb06" value=666.36 size="5" />
</td>
<td>
<input type="number" id="Numb07" value=777.36 size="5" />
</td>
<td>
<input type="number" id="Numb08" value=888.36 size="5" />
</td>
</tr>
<TR>
<td height="20" ColSpan="5"></td>
</TR>
<TR>
<td height="20" ColSpan="2"></td>
<td ColSpan="2" class='alnright'>Multiply:</td>
<td>
<input type="text" id="ActionMulti" value="" size="5" />
</td>
</TR>
<TR>
<td height="20" ColSpan="2"></td>
<td ColSpan="2" class='alnright'>Add:</td>
<td>
<input type="text" id="ActionAdd" value="" size="5" />
</td>
</TR>
<TR>
<td height="20" ColSpan="2"></td>
<td ColSpan="2" class='alnright'>Percentage:</td>
<td>
<input type="text" id="ActionPercentage" value="" size="5" />
</td>
</TR>
<TR>
<td height="20" ColSpan="2"></td>
<td ColSpan="2" class='alnright'>----------</td>
<td>--------</td>
</TR>
<TR>
<td height="20" ColSpan="2"></td>
<td ColSpan="2" class='alnright'>Sum:</td>
<td>
<input type="text" id="Sum" value="" size="5" />
</td>
</TR>
</table>
<br>
<p>Click the button to calculate the data</p>
<button type="button" onclick="calculate_it()">calculate_it</button>
</body>
</html>
Well, I guess you already read all the comments saying the same: It's getElementById not getElementByID. Remember, JavaScript is case sensitive.
What you need to do for run your code successfuly are simple 2 things:
Store all input (number) values in an array.
Use a reduce function to get easy the result for the multiply, sum and percentage.
For example:
function calculate_it() {
var inputs = document.querySelectorAll('input[type="number"]');
var multiply = 0;
var add = 0;
var percentage = 0;
// get the values of each input, map then and return
// a new array with the parsed numbers
var numbers = [].map.call(inputs, function (i) {
return parseFloat(i.value);
});
multiply = numbers.reduce(function (n1, n2) {
return n1 * n2;
});
add = numbers.reduce(function (n1, n2) {
return n1 + n2;
});
percentage = numbers.reduce(function (n1, n2) {
return (n1 / n2) * 100;
});
document.getElementById('ActionMulti').value = multiply.toFixed(2);
document.getElementById('ActionAdd').value = add.toFixed(2);
document.getElementById('ActionPercentage').value = percentage.toFixed(2);
document.getElementById('Sum').value = (multiply + add + percentage).toFixed(2);
}
The toFixed of Number class returns an string representation of the number with the maximum numner of decimals passed as argument. It method round (classic round) the number if is necessary.
Full example
function calculate_it() {
var inputs = document.querySelectorAll('input[type="number"]');
var multiply = 0;
var add = 0;
var percentage = 0;
// get the values of each input, map then and return
// a new array with the parsed numbers
var numbers = [].map.call(inputs, function (i) {
return parseFloat(i.value);
});
multiply = numbers.reduce(function (n1, n2) {
return n1 * n2;
});
add = numbers.reduce(function (n1, n2) {
return n1 + n2;
});
percentage = numbers.reduce(function (n1, n2) {
return (n1 * n2) / 100;
});
document.getElementById('ActionMulti').value = multiply.toFixed(2);
document.getElementById('ActionAdd').value = add.toFixed(2);
document.getElementById('ActionPercentage').value = percentage.toFixed(8);
document.getElementById('Sum').value = (multiply + add + percentage).toFixed(2);
}
input {
width: 100%;
}
<h3>A demonstration of calculators</h3>
<table id="t01">
<caption>Chek this out!</caption>
<tr>
<th>Date</th>
<th>Number 1</th>
<th>Number 2</th>
<th>Number 3</th>
<th>Number 4</th>
</tr>
<tr>
<td>
<input type="text" id="Date01" value="WED21DEC16" size="10" />
</td>
<td>
<input type="number" id="Numb01" value=11.36 size="5" />
</td>
<td>
<input type="number" id="Numb02" value=12.36 size="5" />
</td>
<td>
<input type="number" id="Numb03" value=7.36 size="5" />
</td>
<td>
<input type="number" id="Numb04" value=4.36 size="5" />
</td>
</tr>
<tr>
<td>
<input type="text" id="Date02" value="WED22DEC16" size="10" />
</td>
<td>
<input type="number" id="Numb05" value=8.36 size="5" />
</td>
<td>
<input type="number" id="Numb06" value=6.36 size="5" />
</td>
<td>
<input type="number" id="Numb07" value=10.36 size="5" />
</td>
<td>
<input type="number" id="Numb08" value=8.36 size="5" />
</td>
</tr>
<TR>
<td height="20" ColSpan="5"></td>
</TR>
<TR>
<td height="20" ColSpan="2"></td>
<td ColSpan="2" class='alnright'>Multiply:</td>
<td>
<input type="text" id="ActionMulti" value="" size="5" />
</td>
</TR>
<TR>
<td height="20" ColSpan="2"></td>
<td ColSpan="2" class='alnright'>Add:</td>
<td>
<input type="text" id="ActionAdd" value="" size="5" />
</td>
</TR>
<TR>
<td height="20" ColSpan="2"></td>
<td ColSpan="2" class='alnright'>Percentage:</td>
<td>
<input type="text" id="ActionPercentage" value="" size="5" />
</td>
</TR>
<TR>
<td height="20" ColSpan="2"></td>
<td ColSpan="2" class='alnright'>----------</td>
<td>--------</td>
</TR>
<TR>
<td height="20" ColSpan="2"></td>
<td ColSpan="2" class='alnright'>Sum:</td>
<td>
<input type="text" id="Sum" value="" size="5" />
</td>
</TR>
</table>
<br>
<p>Click the button to calculate the data</p>
<button type="button" onclick="calculate_it()">calculate_it</button>
I'm trying to subtract two totals.
I have one table for incomes, were the final row is the "total incomes" and another table for expenses, with a final row for the "total expenses"
I need to add another function that calculates the total income minus the total expenses. I also need to show a negative amount in case the expenses are greater than the incomes.
My problem is, I don't quite understand how to use the value that its stored on my previous function so I can reuse it on the new one. I'm fairly new to javascript/jquery so I'm having troubles understanding the documentation.
Any guidance on this will be very much appreciated
Here is the js
$(document).ready(function () {
//iterate through each textboxes and add keyup
//handler to trigger sum event
$(".txtA").each(function () {
$(this).keyup(function () {
calculateSumA();
calculateSubstraction();
});
});
});
function calculateSumA() {
var sum = 0;
//iterate through each textboxes and add the values
$(".txtA").each(function () {
//add only if the value is number
if (!isNaN(this.value) && this.value.length != 0) {
sum += parseFloat(this.value);
}
});
//.toFixed() method will roundoff the final sum to 2 decimal places
$("#sumA").html(sum.toFixed(2));
}
$(document).ready(function () {
//iterate through each textboxes and add keyup
//handler to trigger sum event
$(".txt").each(function () {
$(this).keyup(function () {
calculateSum();
calculateSubstraction();
});
});
});
function calculateSum() {
var sum = 0;
//iterate through each textboxes and add the values
$(".txt").each(function () {
//add only if the value is number
if (!isNaN(this.value) && this.value.length != 0) {
sum += parseFloat(this.value);
}
});
//.toFixed() method will roundoff the final sum to 2 decimal places
$("#sum").html(sum.toFixed(2));
}
function calculateSubstraction() {
var subs = calculateSum() - calculateSumA();
$("#subs").html(subs.toFixed(2));
}
here is the html
<body>
<table width="300px" border="1">
<tr>
<td width="40px">1</td>
<td>income</td>
<td>
<input class="txtA" type="text" name="txt" />
</td>
</tr>
<tr>
<td>2</td>
<td>income</td>
<td>
<input class="txtA" type="text" name="txt" />
</td>
</tr>
<tr>
<td>3</td>
<td>income</td>
<td>
<input class="txtA" type="text" name="txt" />
</td>
</tr>
<tr>
<td>4</td>
<td>income</td>
<td>
<input class="txtA" type="text" name="txt" />
</td>
</tr>
<tr>
<td>5</td>
<td>income</td>
<td>
<input class="txtA" type="text" name="txt" />
</td>
</tr>
<tr>
<td>6</td>
<td>income</td>
<td>
<input class="txtA" type="text" name="txt" />
</td>
</tr>
<tr class="income">
<td> </td>
<td align="right">total income:</td>
<td align="center"><span id="sumA">0</span>
</td>
</tr>
</table>
<br/>
<table width="300px" border="1">
<tr>
<td width="40px">1</td>
<td>expense</td>
<td>
<input class="txt" type="text" name="txt" />
</td>
</tr>
<tr>
<td>2</td>
<td>expense</td>
<td>
<input class="txt" type="text" name="txt" />
</td>
</tr>
<tr>
<td>3</td>
<td>expense</td>
<td>
<input class="txt" type="text" name="txt" />
</td>
</tr>
<tr>
<td>4</td>
<td>expense</td>
<td>
<input class="txt" type="text" name="txt" />
</td>
</tr>
<tr>
<td>5</td>
<td>expense</td>
<td>
<input class="txt" type="text" name="txt" />
</td>
</tr>
<tr>
<td>6</td>
<td>expense</td>
<td>
<input class="txt" type="text" name="txt" />
</td>
</tr>
<tr>
<td> </td>
<td align="right">total expenses:</td>
<td align="center"><span id="sum">0</span>
</td>
</tr>
</table>
<br/>
<table width="300px" border="1">
<tr>
<td style="width:40px"></td>
<td style="width:62px">Remaining:</td>
<td align="center"><span id="su">0</span>
</td>
</tr>
</table>
http://jsfiddle.net/gnzLwzuy/5/
I know it could be optimized, as I'm repeating the code too much, but If I change it too much It stops working.
(I have too much to learn...)
Just to complement Guruprasad answer, and to responde directly to how can a function access a value calculated by another function.
The easy way:
1 - declare global variables and use them inside your functions.
var foo;
function calculateSumA() {
....
foo = some value;
}
function OtherFunc() {
....
var localVar = foo;
}
2 - make the functions return a value and store it somewhere other functions can access (e.g a global variable);
Not so simple way:
You can use closures to create the illusion of private members.
I wrote an article on JS Closures. I believe it will help you understand the concept quite well, if you are curious about it: https://usonsci.wordpress.com/2014/10/04/closure-with-javascript/
However you are calling calculateSubstraction on keyup of each textbox just take the value from total of each section and subtract it accordingly as below:
function calculateSubstraction() {
var subs=parseFloat($("#sumA").text()) - parseFloat($("#sum").text())
$("#su").html(subs);
}
DEMO
Update
Here is the more optimized version of your code. I prefer blur event than keyup since its more reliable to calculate and reduces the firing of event on every keypress
$(document).ready(function () {
var income = 0;//variable to hold income
var expense= 0; //variable to hold expense
$(".txtA,.txt").blur(function () { //attach event to multiple elements
$(this).each(function () {//loop through each of them
if (!isNaN(this.value) && this.value.length != 0) {
if($(this).hasClass('txt')) //if it is expense
expense += parseFloat(this.value); //add it to expense
else
income+=parseFloat(this.value); //add it to income
}
});
if($(this).hasClass('txt'))
$("#sum").html(expense.toFixed(2)); //display based on income or expense
else
$("#sumA").html(income.toFixed(2));
calculateSubstraction();//this remains same
});
});
Updated DEMO
DEMO
You need to return a value from the add functions so add
return sum.toFixed(2);
return sum.toFixed(2);
from the two function and did the subtraction from the subtract function
var data = calculateSum();
var dataa = calculateSumA();
var subs = dataa-data;
$("#su").html(subs.toFixed(2));
Just Replace your calculateSubstraction() function with this :
function calculateSubstraction() {
var Income = parseFloat($('#sumA').html());
var Expense = parseFloat($('#sum').html());
var subs = Income - Expense;
$("#su").html(subs.toFixed(2));
}
Using jQuery, you can have a simple calculation like
jQuery(function() {
var sum = {
income: 0,
deduction: 0
};
$('input.entry').keyup(function() {
var $table = $(this).closest('table'),
total = 0;
$table.find('input.entry').each(function() {
total += +this.value || 0;
});
$table.find('span.total').html(total)
sum[$table.data('type')] = total;
$('#su').html(sum.income - sum.deduction);
})
})
body {
font-family: sans-serif;
}
table {
border-collapse: collapse;
border-color: white;
background-color: powderblue;
}
input.entry {
background-color: #FEFFB0;
font-weight: bold;
text-align: right;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table width="300px" border="1" class="entry" data-type="income">
<tr>
<td width="40px">1</td>
<td>income</td>
<td>
<input class="txtA entry" type="text" name="txt" />
</td>
</tr>
<tr>
<td>2</td>
<td>income</td>
<td>
<input class="txtA entry" type="text" name="txt" />
</td>
</tr>
<tr>
<td>3</td>
<td>income</td>
<td>
<input class="txtA entry" type="text" name="txt" />
</td>
</tr>
<tr>
<td>4</td>
<td>income</td>
<td>
<input class="txtA entry" type="text" name="txt" />
</td>
</tr>
<tr>
<td>5</td>
<td>income</td>
<td>
<input class="txtA entry" type="text" name="txt" />
</td>
</tr>
<tr>
<td>6</td>
<td>income</td>
<td>
<input class="txtA entry" type="text" name="txt" />
</td>
</tr>
<tr class="income">
<td> </td>
<td align="right">total income:</td>
<td align="center"><span class="total">0</span>
</td>
</tr>
</table>
<br/>
<table width="300px" border="1" class="entry" data-type="deduction">
<tr>
<td width="40px">1</td>
<td>expense</td>
<td>
<input class="txt entry" type="text" name="txt" />
</td>
</tr>
<tr>
<td>2</td>
<td>expense</td>
<td>
<input class="txt entry" type="text" name="txt" />
</td>
</tr>
<tr>
<td>3</td>
<td>expense</td>
<td>
<input class="txt entry" type="text" name="txt" />
</td>
</tr>
<tr>
<td>4</td>
<td>expense</td>
<td>
<input class="txt entry" type="text" name="txt" />
</td>
</tr>
<tr>
<td>5</td>
<td>expense</td>
<td>
<input class="txt entry" type="text" name="txt" />
</td>
</tr>
<tr>
<td>6</td>
<td>expense</td>
<td>
<input class="txt entry" type="text" name="txt" />
</td>
</tr>
<tr>
<td> </td>
<td align="right">total expenses:</td>
<td align="center"><span class="total">0</span></td>
</tr>
</table>
<br/>
<table width="300px" border="1">
<tr>
<td style="width:40px"></td>
<td style="width:62px">Remaining:</td>
<td align="center"><span id="su">0</span>
</td>
</tr>
</table>
I've made a pure Javascript version of your code, and added two new functionalities:
A button to dynamically add new rows to the income and expense tables.
And remove the ability of user adding anything other than numbers to the textfields.
The full commented code is below:
/* when all elements of the page are available */
document.addEventListener('DOMContentLoaded', function() {
/* get the tables income and expense, and the 'total' fields */
var income = document.getElementById('income'),
expense = document.getElementById('expense'),
totalIncome = document.getElementById('totalIncome'),
totalExpense = document.getElementById('totalExpense'),
total = document.getElementById('total');
/* create the calculate function */
function calculate(e) {
/* get all the textfields of each table */
var incomes = [].slice.call(income.querySelectorAll('input')),
expenses = [].slice.call(expense.querySelectorAll('input'));
/* calculate the sum of the fields by using
- map to convert the values to numbers
- and reduce to sum those values */
var sumIncome = incomes.map(function(el) {
/* don't allow users to input other values than numbers */
el.value = el.value.replace(/[^0-9\.]/g, '');
return Number(el.value);
}).reduce(function(a, b) {
return a + b;
});
var sumExpense = expenses.map(function(el) {
/* don't allow users to input other values than numbers */
el.value = el.value.replace(/[^0-9\.]/g, '');
return Number(el.value);
}).reduce(function(a, b) {
return a + b;
});
/* change the totalIncome and totalExpense labels */
totalIncome.textContent = sumIncome;
totalExpense.textContent = sumExpense;
/* change the total remaining label */
total.textContent = sumIncome - sumExpense;
}
/* add the event handlers to the oninput event to both tables
they will call the calculate function above when they happen */
income.addEventListener('input', calculate);
expense.addEventListener('input', calculate);
/* this is a bonus, I've added 'new' buttons to dynamically add more rows */
document.addEventListener('click', function(e) {
var el = e.target;
if (el.className === 'new') {
var table = el.parentNode.parentNode.parentNode,
tr = document.createElement('tr');
tr.innerHTML = '<td>' + [].slice.call(table.querySelectorAll('tr')).length + '</td>\
<td>income</td>\
<td>\
<input class="txtA" type="text" />\
</td>';
table.insertBefore(tr, el.parentNode.parentNode);
}
});
});
body {
font-family: sans-serif;
}
table {
border-collapse: collapse;
border-color: white;
background-color: powderblue;
}
.txt,
.txtA {
background-color: #FEFFB0;
font-weight: bold;
text-align: right;
}
<table id='income' width="300px" border="1">
<tr>
<td width="40px">1</td>
<td>income</td>
<td>
<input class="txtA" type="text" name="txt" />
</td>
</tr>
<tr>
<td>2</td>
<td>income</td>
<td>
<input class="txtA" type="text" name="txt" />
</td>
</tr>
<tr>
<td>3</td>
<td>income</td>
<td>
<input class="txtA" type="text" name="txt" />
</td>
</tr>
<tr>
<td>4</td>
<td>income</td>
<td>
<input class="txtA" type="text" name="txt" />
</td>
</tr>
<tr>
<td>5</td>
<td>income</td>
<td>
<input class="txtA" type="text" name="txt" />
</td>
</tr>
<tr>
<td>6</td>
<td>income</td>
<td>
<input class="txtA" type="text" name="txt" />
</td>
</tr>
<tr class="income">
<td>
<button class="new">new</button>
</td>
<td align="right">total income:</td>
<td align="center"><span id="totalIncome">0</span>
</td>
</tr>
</table>
<br/>
<table id='expense' width="300px" border="1">
<tr>
<td width="40px">1</td>
<td>expense</td>
<td>
<input class="txt" type="text" name="txt" />
</td>
</tr>
<tr>
<td>2</td>
<td>expense</td>
<td>
<input class="txt" type="text" name="txt" />
</td>
</tr>
<tr>
<td>3</td>
<td>expense</td>
<td>
<input class="txt" type="text" name="txt" />
</td>
</tr>
<tr>
<td>4</td>
<td>expense</td>
<td>
<input class="txt" type="text" name="txt" />
</td>
</tr>
<tr>
<td>5</td>
<td>expense</td>
<td>
<input class="txt" type="text" name="txt" />
</td>
</tr>
<tr>
<td>6</td>
<td>expense</td>
<td>
<input class="txt" type="text" name="txt" />
</td>
</tr>
<tr>
<td>
<button class="new">new</button>
</td>
<td align="right">total expenses:</td>
<td align="center"><span id="totalExpense">0</span>
</td>
</tr>
</table>
<br/>
<table width="300px" border="1">
<tr>
<td style="width:40px"></td>
<td style="width:62px">Remaining:</td>
<td align="center"><span id="total">0</span>
</td>
</tr>
</table>
I need to create HTML table using jQuery dynamically and also I need to make multiplication between rows and columns. My rows is yield and column is price. I have two variables a and b.
var a; //represent price
var b; // represent yield
Now I need to create table and multiplication like this:
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<th rowspan="2" scope="col">Yield</th>
<th colspan="7" scope="col">Price</th>
</tr>
<tr>
<td>a-1.5</td>
<td>a-1</td>
<td>a-0.5</td>
<td>a</td>
<td>a+0.5</td>
<td>a+1</td>
<td>a+1.5</td>
</tr>
<tr>
<th scope="row">b-500</th>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<th scope="row">b-400</th>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<th scope="row">b-300</th>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<th scope="row">b-200</th>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<th scope="row">b-100</th>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<th scope="row">b</th>
<td> </td>
<td> </td>
<td> </td>
<td>a*b</td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<th scope="row">b+100</th>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<th scope="row">b+200</th>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<th scope="row">b+300</th>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<th scope="row">b+400</th>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<th scope="row">b+500</th>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
</table>
<p> </p>
http://jsfiddle.net/nexetdad/
So columns is based on price +/- and rows are based on yield +/-. How I can create with JavaScript table matrix so every cell need to be calculated (a*b)?
Please give me some ideas. I don't know where to start.
I think you are lack of DOM skill.
You can refer it.
<head>
<script type="text/javascript">
function addlabel(s,n){
if (n > 0){
return s + "+" + String(n);
}
else if (n < 0){
return s + String(n);
}
else{
return s;
}
}
function multiplicationTable(){
x = document.getElementById("i1").value;
x = parseInt(x);
y = document.getElementById("i2").value;
y = parseInt(y);
var table = '<table border="1px"><thead>';
table += '<tr><th></th>'
for (var a = -1.5; a<= 1.5 ; a+=0.5){
table += '<th>'+ addlabel("a", a) +'</th>';
}
table += '</tr></thead><tbody>'
// add num
for (var b = y-500, ob = y; b<= y+500 ; b+=100){
table += "<tr>";
table += "<td>" + addlabel("b",b-ob) + "</td>"
for (var a = x-1.5; a<= x+1.5 ; a+=0.5){
table += '<td>'+ a*b +'</td>';
}
table += "</tr>";
}
return table + '</tbody></table>';
}
function build(){
document.getElementById('here').innerHTML = multiplicationTable();
}
</script>
</head>
<body>
<form name="f">
<input type="text" value ="15" name="r" id="i1">
<input type="text" value ="5000" name="c" id="i2">
<input type="button" value="make table" onclick="build()">
</form>
<div id="here">
</div>
</body>
https://jsfiddle.net/tonypythoneer/z5reeomj/2/
Although i dont know much about js and jquery you can mix them and this could be done. Go for nested for loop for creating your table and use append() of jquery for appending the content of table and simple multiplication.
By the way this can done easily using php.