I trying to calculate some rows (input fields) but it seams to hard for me :(.
The html code i have looks like this:
<table>
<tr>
<td>
<input name="Field_Price_1" id="Field_Price_1" value="20.55" type="text">
<input name="Field_Amount_1" id="Field_Amount_1" type="text">
<input name="Field_SubTotal_1" id="Field_SubTotal_1" type="text">
</td>
</tr>
<tr>
<td>
<input name="Field_Price_2" id="Field_Price_2" value="17.55" type="text">
<input name="Field_Amount_2" id="Field_Amount_2" type="text">
<input name="Field_SubTotal_2" id="Field_SubTotal_2" type="text">
</td>
</tr>
<tr>
<td>
<input name="Field_Price_3" id="Field_Price_3" value="94.20" type="text">
<input name="Field_Amount_3" id="Field_Amount_3" type="text">
<input name="Field_SubTotal_3" id="Field_SubTotal_3" type="text">
</td>
</tr>
<tr>
<td>
<input name="Field_Price_4" id="Field_Price_4" value="12.10" type="text">
<input name="Field_Amount_4" id="Field_Amount_4" type="text">
<input name="Field_SubTotal_4" id="Field_SubTotal_4" type="text">
</td>
</tr>
<tr>
<td>
<input name="Field_Price_5" id="Field_Price_5" value="7.45" type="text">
<input name="Field_Amount_5" id="Field_Amount_5" type="text">
<input name="Field_SubTotal_5" id="Field_SubTotal_5" type="text">
</td>
</tr>
So i would put the sum from all input fields "Field_Price_" in the following span by triggering "keyup" from each Field_Amount_".
<table>
<tr>
<td><span id="PrintSum">0.00</span></td>
</tr>
The following i tried:
var total = 0;
var Price = $('input[id^=Field_Price_]').val();
$.each($(Price), function(){
total += $(this).val();
});
$('#PrintSum').text(total);
So that won't work.
Do any know what is the problem? Thank you very much!
try something like this,Fiddle
var total = 0;
var Price = $('input[id^=Field_Price_]');
$.each($(Price), function(){
total += parseInt($(this).val());
});
$('#PrintSum').text(total);
use this javascript
$(':input[id^="Field_Price_"]').keyup(function() {
var total = 0;
var $inputs = $(':input[id^="Field_Price_"]');
$inputs.each(function (index)
{
total += parseFloat($(this).val());
});
alert(total);
$('#PrintSum').text(total);
});
jsFiddle
What about this solution:
var $prices = $('input[id^=Field_Price_]'),
$amounts = $('input[id^=Field_Amount_]');
$prices.add($amounts).on('keyup', function() {
var total = 0;
$prices.each(function() {
total += $(this).val() * $(this).next().val() || 0;
});
$('#PrintSum').text(total.toFixed(2));
})
.trigger('keyup');
http://jsfiddle.net/UFSvF/
Here changing the price as well as an amount triggers total price recalculation.
I guess you should be parse the input value to an float.
var total = 0;
var Price = $('input[id^=Field_Price_]').val();
$.each($(Price), function(){
total += parseFloat($(this).val());
});
$('#PrintSum').text(total);
On jsfiddle, an example not using jquery, but you could modify to do testing there
var prices = document.querySelectorAll("[id^=Field_Price]"),
ammounts = document.querySelectorAll("[id^=Field_Amount]"),
subTotals = document.querySelectorAll("[id^=Field_SubTotal]"),
printSum = document.getElementById("PrintSum");
function sumIt() {
var total = 0;
Array.prototype.forEach.call(prices, function (price, index) {
var subTotal = (parseFloat(price.value) || 0) * (parseFloat(ammounts[index].value) || 0);
subTotals[index].value = subTotal.toFixed(2);
total += subTotal;
});
printSum.textContent = total.toFixed(2);
}
Array.prototype.forEach.call(prices, function (input) {
input.addEventListener("keyup", sumIt, false);
});
Array.prototype.forEach.call(ammounts, function (input) {
input.addEventListener("keyup", sumIt, false);
});
sumIt();
Here is a jquery version of above, on jsfiddle
var prices = $("input[id^=Field_Price_]"),
amounts = $("input[id^=Field_Amount_]"),
subTotals = $("input[id^=Field_SubTotal_]"),
printSum = $("#PrintSum");
function sumIt() {
var total = 0;
prices.each(function(index, price) {
var subTotal = (parseFloat(price.value) || 0) * (parseFloat(amounts.eq(index).val()) || 0);
subTotals.eq(index).val(subTotal.toFixed(2));
total += subTotal;
});
printSum.text(total.toFixed(2));
}
prices.on("keyup", sumIt);
amounts.on("keyup", sumIt);
sumIt();
I will modify my pure javascript version soon to show you how your further questioning can be achieved, without the need of including jquery.
It has now been updated so you can see how it works
And a jsperf showing the construction performance of the two
Related
I am trying to calculate qty total from the gridview for checked row checkbox but not able to get the checkbox control in my javascript. How can I get the Checkbox control from below generated Gridview table row in Javascript? I had attached my script below which get nothing on the script.
<table cellspacing="0" cellpadding="1" rules="all" border="1" id="grdView" style="background-color:#F2F4FF;width:100%;border-collapse:collapse;">
<tr>
<td align="center">
<span class="chkSelected" style="display:inline-block;border-style:None;"><input id="grdView_ctl02_chkSelect" type="checkbox" name="grdView$ctl02$chkSelect" /></span>
<input type="hidden" name="grdView$ctl02$hdDocId" id="grdView_ctl02_hdDocId" value="DO0002" />
<input type="hidden" name="grdView$ctl02$hdScope" id="grdView_ctl02_hdScope" value="Dlv" />
<input type="hidden" name="grdView$ctl02$hdDocType" id="grdView_ctl02_hdDocType" value="DO" />
<input type="hidden" name="grdView$ctl02$hdRefNo" id="grdView_ctl02_hdRefNo" />
<input type="hidden" name="grdView$ctl02$hdServiceType" id="grdView_ctl02_hdServiceType" />
<input type="hidden" name="grdView$ctl02$hdQty" id="grdView_ctl02_hdQty" />
<input type="hidden" name="grdView$ctl02$hdWeight" id="grdView_ctl02_hdWeight" />
</td>
</tr>
</table>
function calculateTotal()
{
var sum = 0.00;
var itemsum = 0.00;
var gv = document.getElementById('grdView');
for (var row = 1; row < gv.rows.length; row++) {
var cb = gv.rows[row].cell[0].childNodes[0].find('input[type="checkbox"]');
if (cb.checked) {
var quantity = gv.rows[row].cells[8].innerText;
try {
sum += new Number(quantity);
} catch (err) {
alert(quantity);
}
}
}
alert(sum.toString());
return false;
}
I wasted couple of days to get my correct output as below code. Hope this will help and time saving to those javascript beginner developer (like me :)). Happy coding.
function calculateTotal()
{
var sum = 0.00;
var gv = document.getElementById('grdView');
for (var row = 1; row < gv.rows.length; row++) {
const collection = gv.rows[row].cells[0].children;
var cb = collection[0].firstChild;
if (cb.checked) {
var quantity = gv.rows[row].cells[8].innerText;
try {
sum += new Number(quantity);
} catch (err) {
//how to alert(quantity);
}
}
}
var lbltotal= document.getElementById('lblTotalQty');
lbltotal.innerHTML = sum.toString();
return false;
}
I do not understand javascript at all, I study as needed and I need help
I need to sum up the values of certain columns of a table, the rows of which are marked with a checkbox
For example: I mark the checkbox in two rows of the table and the sum of 3,4 and 5 columns is summed up and displayed somewhere on the page
Now I managed to find a piece of code that summarizes the value of the checked checkboxes in the form, and displays it on the page
I need help in replacing the part that receives the "value" of the input, with the one that gets the values of the cells in the stob = head of the table and sums them
Here is this code
var
$form = $("#out_form"),
$allCheckboxes = $("input:checkbox", $form),
$sumOut = $("#checked-sum"),
$countOut = $("#checked-count");
$allCheckboxes.change(function() {
var
sum = 0,
count = 0;
$allCheckboxes.each(function(index, el) {
var
$el = $(el),
val;
if ($el.is(":checked")) {
count++;
val = parseFloat($el.val());
if (!isNaN(val)) {
sum += val;
}
}
});
$sumOut.text(sum);
$countOut.text(count);
});
HTML
<form action="" method="post" id="out_form">
<input type="hidden" name="next" value="{{next}}"/>
<button type="submit">Check</button>
<span id="checked-sum">0</span>
<span id="checked-count">0</span>
{%csrf_token%}
<div class="table-view__container">
<table class="table-view__table">
<tbody class="table-view__body">
{% for out in filter.qs %}
<tr>
<td>
<label class="custom_Label">
<input type="checkbox" name="checked" value="{{ out.id }}">
<span class="checkmark"></span>
</label>
</td>
<td>{{out.date|date:"d(D).m.Y"}}</td>
<td>{{out.ts}}</td>
<td>{{out.pl}}</td>
<td>{{out.rem}}</td>
<td>{{out.comment}}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</form>
It is necessary to sum these 3 columns:
...
<td>{{out.ts}}</td>
<td>{{out.pl}}</td>
<td>{{out.rem}}</td>
...
UPD:
I managed to display the amount with the checkbox active, but only the first line:
var
$form = $("#out_form"),
$table = $(".table-view"),
$allCheckboxes = $("input:checkbox", $form),
$sumOut = $("#checked-sum"),
$countOut = $("#checked-count");
$allCheckboxes.change(function() {
var
sum = 0,
count = 0;
$allCheckboxes.each(function(index, el) {
var
$el = $(el),
val;
if ($el.is(":checked")) {
count++;
$form.each(function () {
var val1 = parseInt(document.querySelector(".ts", this).innerHTML,10);
var val2 = parseInt(document.querySelector(".pl", this).innerHTML,10);
var val3 = parseInt(document.querySelector(".rem", this).innerHTML,10);
var total = (val1 * 1) + (val2 * 1) + (val3 * 1);
sum += total;
});
if (!isNaN(val)) {
sum += total;
}
}
});
$sumOut.text(sum);
$countOut.text(count);
});
JavaScript can be confusing, its definitely not an easy programming language. Sorry for not using your code, but I think its overcomplicating things.
So mainly what this code does is to trigger a function using event handlers on all checkboxes, that sums or substracts from the result variable depending if they are checked or unchecked and then show the result in a <span> tag.
Some key points
I used document.querySelectorAll('input[type=checkbox]') to get all the checkbox elements.
The following code is to create one event handler for each checkbox element:
boxes.forEach((box) => {
box.addEventListener("change", function() {
The input checkbox element lives inside a <td></td>, so this.closest('td').nextElementSibling is necessary to get the parent tag and then with the help of nextElementSibling we can get the next <td> element of the table which has the value we need to sum or substract.
Snippet
var boxes = document.querySelectorAll('input[type=checkbox]'),
show = document.getElementById('showResult'), result = 0;
boxes.forEach((box) => {
box.addEventListener("change", function() {
var firstElement = this.closest('td').nextElementSibling,
secondElement = firstElement.nextElementSibling,
firstValue = parseInt(firstElement.innerHTML),
secondValue = parseInt(secondElement.innerHTML);
var sum = firstValue + secondValue;
this.checked ? result += sum : result -= sum;
show.innerHTML = result;
});
});
td {
border: 1px solid #dddddd;
text-align: left;
width:50px;
text-align:center;
}
span{
font-size:20px;
}
<table id="table">
<tr>
<td><input type="checkbox" id="box1" /></td>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td><input type="checkbox" id="box2" /></td>
<td>3</td>
<td>4</td>
</tr>
</table>
<br>
<br>
<span>Result: </span><span id="showResult">0</span>
Hey guys looking for some assistance with changing the color of text based on value. If the value is zero or negative I want it to be red, and if the value is + I want it to be green. Below is just a little bit of code from the full html but I think these are the key parts. Here is a JSFiddle As you can see the table is dynamic. As you input data into the starting amount it will automatically calculate it for the ending amount. The starting amount adds to the bill amount which produces the total amount number. I am also not sure if the event "onchange" is correct. Thank you for your input and advise in advanced.
<p><b>Starting Amount: $ <input id="money" type="number" onkeyup="calc()"></b></p>
<table>
<tr>
<th>Bill Ammount</th>
</tr>
<tr>
<td><input type="number" class="billAmt" id="billAmt" onkeyup="calc()"> </td>
</tr>
</table>
<input type="hidden" id="total" name="total" value="0">
<p><b>Ending Amount: $ <span id="totalAmt" onchange="colorChange(this)">0</span></b></p>
<script type="text/Javascript">
var myElement = document.getElementById('totalAmt');
function colorChange() {
if('myElement' > 0) {
totalAmt.style.color = 'green';
} else {
totalAmt.style.color = 'red';
}
}
function calc() {
var money = parseInt(document.querySelector('#money').value) || 0;
var bills = document.querySelectorAll('table tr input.billAmt') ;
var billTotal = 0;
for (i = 0; i < bills.length; i++) {
billTotal += parseInt(bills[i].value) || 0;
}
totalAmt.innerHTML = money + billTotal;
}
</script>
You can reach the desired result using just one function. Instead of checking the DOM element's innerHTML or textContext to get the amount, just refer to the variables holding it.
var myElement = document.getElementById('totalAmt');
function calc() {
var money = parseInt(document.querySelector('#money').value) || 0;
var bills = document.querySelectorAll('table tr input.billAmt');
var billTotal = 0;
for (i = 0; i < bills.length; i++) {
billTotal += parseInt(bills[i].value) || 0;
}
totalAmt.innerHTML = money + billTotal;
myElement.style.color = money + billTotal <= 0 ? 'red' : 'green';
}
<p><b>Starting Amount: $ <input id="money" type="number" onkeyup="calc()"></b></p>
<table>
<tr>
<th>Bill Ammount</th>
</tr>
<tr>
<td><input type="number" class="billAmt" id="billAmt" onkeyup="calc()"></td>
</tr>
</table>
<input type="hidden" id="total" name="total" value="0">
<p><b>Ending Amount: $ <span id="totalAmt">0</span></b></p>
use myElement.innerHTML instead of myElement in the if condition and invoke the changeColor function at last of calc
var myElement = document.getElementById('totalAmt');
function colorChange() {
if (myElement.innerHTML <= 0) {
totalAmt.style.color = 'red';
} else {
totalAmt.style.color = 'green';
}
}
function calc() {
var money = parseInt(document.querySelector('#money').value) || 0;
var bills = document.querySelectorAll('table tr input.billAmt');
var billTotal = 0;
for (i = 0; i < bills.length; i++) {
billTotal += parseInt(bills[i].value) || 0;
}
totalAmt.innerHTML = money + billTotal;
colorChange();
}
<p><b>Starting Amount: $ <input id="money" type="number" onkeyup="calc()"></b></p>
<table>
<tr>
<th>Bill Ammount</th>
</tr>
<tr>
<td><input type="number" class="billAmt" id="billAmt" onkeyup="calc()"></td>
</tr>
</table>
<input type="hidden" id="total" name="total" value="0">
<p><b>Ending Amount: $ <span id="totalAmt">0</span></b></p>
A couple issues with your original code:
1 - you were checking if the string myElement was greater than zero, instead of the innerHTML of the element you selected.
2 - using innerHTML() to change the contents of an element doesn't fire an onchange event. In my code, I call your colorChange function at the end of the calc function, so if you decide to add another field to it (tax or something), it will be called after the total is calculated.
function colorChange() {
var myElement = document.getElementById('totalAmt');
if (myElement.innerHTML > 0) {
totalAmt.style.color = 'green';
} else {
totalAmt.style.color = 'red';
}
}
function calc() {
var money = parseInt(document.querySelector('#money').value) || 0;
var bills = document.querySelectorAll('table tr input.billAmt');
var billTotal = 0;
for (i = 0; i < bills.length; i++) {
billTotal += parseInt(bills[i].value) || 0;
}
totalAmt.innerHTML = money + billTotal;
colorChange()
}
<p><b>Starting Amount: $ <input id="money" type="number" onkeyup="calc()"></b></p>
<table>
<tr>
<th>Bill Ammount</th>
</tr>
<tr>
<td><input type="number" class="billAmt" id="billAmt" onkeyup="calc()"> </td>
</tr>
</table>
<input type="hidden" id="total" name="total" value="0">
<p><b>Ending Amount: $ <span id="totalAmt">0</span></b></p>
I'm sorry to post this question but I'm kinda newbie when it comes to js. I have created a simple page that will compute charging transactions, so what it will do is to simply multiply the Quantity and Price to .25%. But here is the trick, if the total product is less than 50 the Charge field should default to 50 and that's where I'm kinda lost,
here is my code:
<tr>
<td width="144">Quantity:</td>
<td width="63"><input type="text" name="quantity" id="quantity" size="8"/></td>
</tr>
<tr>
<td>Price:</td>
<td><input type="text" name="price" id="price" size="8"/></td>
</tr>
<tr>
<td colspan="4"><strong>Charges:</strong></td>
</tr>
<tr>
<td>Charge:</td>
<td><input style="color:#F00" type="text" name="charge" id="charge" size="8" readonly="readonly" /></td>
<td colspan="2">Quantity x Price x .25% OR 20 whichever is higher</td>
</tr>
here is the js that i managed to have,
$(function () {
$("#quantity, #price").keyup(function () {
var q = parseFloat($("#quantity").val()); // Quantity
var p = parseFloat($("#price").val()); // Price
if (isNaN(q) || isNaN(p) || q<=0 || p <= 0) {
$("#charge").val('');
return false;
}
$("#charge").val((q * p * 0.0025).toFixed(3)); // Charge
});
});
Put the total in a variable and test it before putting it into the DOM:
$(function () {
$("#quantity, #price").keyup(function () {
var q = parseFloat($("#quantity").val()); // Quantity
var p = parseFloat($("#price").val()); // Price
if (isNaN(q) || isNaN(p) || q<=0 || p <= 0) {
$("#charge").val('');
return false;
}
var total = q * p * 0.0025;
if (total < 50) {
total = 50;
}
$("#charge").val(total.toFixed(3)); // Charge
});
});
Another way is to use Math.max():
$("#charge").val(Math.max(50, q * p * 0.0025).toFixed(3)); // Charge
I'm using the following code to take the value of one field, subtract it from the value of another field and display the result.
$(document).ready(function() {
var numIn;
var numOut;
var total;
$('#submit').click(function() {
numIn = $('input.in').val();
numOut = $('input.out').val();
total = numIn-numOut;
$('span').remove();
$('body').append('<span>£'+total+'</span>');
$('span').fadeIn(250);
});
});
I want to create a sort of income/expenditure calculator. so my question is, say I had multiple income fields and multiple expenditure fields how would I take the total value from the income fields away from the total value of the expenditure fields.
Here is an example form in case I haven't been clear.
<form>
<input class="in" type="text">
<input class="in" type="text">
<input class="in" type="text">
<input class="in" type="text">
<input class="out" type="text">
<input class="out" type="text">
<input class="out" type="text">
<input class="out" type="text">
<input type="submit" id="submit" value="Submit">
You could loop over the .in and .out fields, and add their values as you go.
Example: http://jsfiddle.net/tXPeg/3/
var numIn = 0;
var numOut = 0;
var total;
$('#submit').click(function() {
$('input.in').each(function() {
return numIn += (parseFloat(this.value) || 0);
});
$('input.out').map(function() {
return numOut += (parseFloat(this.value) || 0);
});
total = numIn - numOut;
$('span').remove();
$('body').append('<span>£' + total + '</span>');
$('span').fadeIn(250);
return false;
});
EDIT: Changed to use parseFloat() instead of parseInt().
Actually after testing a little further the only problem is that if one or more fields are empy it returns 'NaN'.
I tried adding conditional statements to check that the field had a value but no luck:
Feel free to edit my example: http://jsfiddle.net/QaEcD/3/
$('#submit').click(function() {
var numIn = 0;
var numOut = 0;
var total = 0;
$('input.in').each(function() {
if($(this).val().length !== 0){
return numIn = numIn + parseInt(this.value);
});
});
$('input.out').map(function() {
if($(this).val().length !== 0){
return numOut = numOut + parseInt(this.value);
});
});
total = numIn-numOut;
$('span').remove();
$('body').append('<span>£'+total+'</span>');
$('span').fadeIn(250);
return false;
});
});