How could I get the Final Total based on the sum of a checkbox value and the contents of a textbox?
JSFiddle example
My HTML:
<table border="1">
<tr><td>10<input type="checkbox" class="tot_amount" value="10"></td><td>10<input id="os1" type="text"></td></tr>
<tr><td>20<input type="checkbox" class="tot_amount" value="20"></td><td>20<input id="os2" type="text" ></td></tr>
<tr><td>Total<input type="text" id="total1" readonly></td><td>Total2<input id="total2" type="text" readonly></td></tr>
</table>
Final Total<input type="text" id="final" readonly >
And Javascript:
$(".tot_amount").click(function(event) {
var total = 0;
$(".tot_amount:checked").each(function() {
total += parseInt($(this).val());
});
if (total == 0) {
$('#total1').val('');
}
else {
$('#total1').val(total);
}
});
$('#os1, #os2').on('input',function(){
var os1= parseFloat($('#os1').val()) || 0;
var os2= parseFloat($('#os2').val()) || 0;
$('#total2').val(os1 + os2);
});
Just bind a focus event and do it -
$('#final').bind('focus',function(){
$(this).val(parseInt($('#total1').val())+parseInt($('#total2').val()));
});
LIVE http://jsfiddle.net/mailmerohit5/h43te3z6/
Related
I Want to hide element if another div's length is greater than 0, otherwise show the div
i have this code but it is not working for me :(
<div id="myid">90.00</div>
<div class="myclass">99.00</div>
JS code
$(document).ready(function() {
if($('#myid').length > 2){
$('.myclass').hide();
}
});
First edit your question by your new detail;
Then set your condition inside your updateTotalFinal function
jQuery(document).ready(function() {
function updateTotalFinal(){
const subtotalValue = +jQuery('.wpforms-payment-total').text().replace(/^[^0-9,.]+/, "").match( /^[0-9,.]+/g, '');
let totalValue = subtotalValue;
const totalFinalElem = jQuery("#totalfinal");
jQuery("input.change-total:checked").each(function() {
const $this = jQuery(this);
if ($this.is("[data-method=add]")) {
totalValue = totalValue * $this.data("amount");
} else if ($this.is("[data-method=multiply]")) {
totalValue += subtotalValue * $this.data("amount");
}
});
totalFinalElem.text(`${totalValue.toFixed(2)}`);
// IF YOU WANT CHECK THAT ANY VALUE FOR totalfinal IS EXIST USE THIS
if($('#totalfinal').text().length ){
$('.wpforms-payment-total').hide();
}
// IF YOU WANT CHECK THAT totalfinal IS GREATHER THAN ZERO USE THIS
/* if(parseInt( $('#totalfinal').text()) > 0 ){
$('.wpforms-payment-total').hide();
} */
}
jQuery("input.change-total").on("change", function() {
updateTotalFinal();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wpforms-payment-total">
97
</div>
<tr>
<td>
<input type="checkbox" class="change-total" name="myBox2" size="12" data-amount="0.15" data-method="multiply" value="100" />
With Two Coat + 15%
</td>
<td>
<input type="checkbox" class="change-total" name="myBox3" size="12" id="myCheck" data-amount="0.9" data-method="add" />
With My Own Paint
</td>
</tr>
<br>
<b><span id="totalfinal"></span></b>
i have this code and want to hide
class "wpforms-payment-total" when "totalfinal" is calculated
<div class="wpforms-payment-total">
97
</div>
<tr>
<td>
<input type="checkbox" class="change-total" name="myBox2" size="12" data-amount="0.15" data-method="multiply" value="100" />
With Two Coat + 15%
</td>
<td>
<input type="checkbox" class="change-total" name="myBox3" size="12" id="myCheck" data-amount="0.9" data-method="add" />
With My Own Paint
</td>
</tr>
<br>
<b><span id="totalfinal"></span></b>
JS
jQuery(document).ready(function() {
function updateTotalFinal(){
const subtotalValue = +jQuery('.wpforms-payment-total').text().replace(/^[^0-9,.]+/, "").match( /^[0-9,.]+/g, '');
let totalValue = subtotalValue;
const totalFinalElem = jQuery("#totalfinal");
jQuery("input.change-total:checked").each(function() {
const $this = jQuery(this);
if ($this.is("[data-method=add]")) {
totalValue = totalValue * $this.data("amount");
} else if ($this.is("[data-method=multiply]")) {
totalValue += subtotalValue * $this.data("amount");
}
});
totalFinalElem.text(`$ ${totalValue}`);
}
jQuery("input.change-total").on("change", function() {
updateTotalFinal();
});
});
$(document).ready(function() {
if($('#totalfinal').text() > 0){
$('.myclass').hide();
}
});
This is a table for user to record Expenses and Amount. User can add table cell to record more items with the amount. After user key in the Amount, it will show 7% tax at beside and total amount at the top. But now i am facing 2 problems.
If user added 2 items, and input the 2 items' amount, then if they deleted the row, the total amount will not deduct after the row is deleted.
the tax will only added in first row. I want to do it in each row with 7% tax with each item's amount.
So can i know how to solve this 2 problems?
function validate(evt) {
var theEvent = evt || window.event;
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode(key);
var regex = /[0-9]|\./;
if (!regex.test(key)) {
theEvent.returnValue = false;
if (theEvent.preventDefault) theEvent.preventDefault();
}
}
function force2decimals(event) {
var value = $(event).val();
var format_val = parseFloat(value).toFixed(2);
$(event).val(format_val);
}
//<----------------------2 Decimal force END-------------------->
// +
function mFunction() {
document.getElementById("rowrow").insertRow(-1).innerHTML =
'<tr><td></td><td><output id="gst">0.00</output></td><td><input type="text" name="Amount[]" id="columninput" class="input" oninput="myFunction(this.value)" placeholder="Amount" style="font-size:14px;" min="0" lang="en-150" onchange="force2decimals(this)" onkeypress="validate(event)" inputmode="numeric"></td></tr>';
}
// -
function remove() {
var x = document.getElementById("rowrow").rows.length;
if (x == 1) {} else {
document.getElementById("rowrow").deleteRow(-1);
};
}
function myFunction() {
const ele = document.querySelectorAll('input.input');
let sum = 0;
ele.forEach(input => {
sum += input.value ? parseFloat(input.value) : 0;
});
document.getElementById('result').textContent = sum.toFixed(2);
document.getElementById('gst').textContent = (sum * 0.07).toFixed(2);
}
.css-serial {
counter-reset: serial-number;
}
.css-serial td:first-child:before {
counter-increment: serial-number;
content: counter(serial-number);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<div id="container">
<div id="body">
<br>
<div class="row">
<div class="css-serial" style="overflow-x:auto;">
<table id="rowrow">
<tr>
<td id="number"></td>
<td><output id="gst">0.00</output></td>
<td><input type="text" name="Amount[]" class="input" oninput="myFunction(this.value)" id="columninput" placeholder="Amount" style="font-size:14px;" min="0" lang="en-150" onchange="force2decimals(this)" onkeypress='validate(event)' inputmode='numeric'
required></td>
Total Amount <output id="result"> 0.00 </output>
<input type="button" id="slipbutton1" onclick="mFunction();" name='add' value="+" />
<input type="button" id="slipbutton2" onclick="remove();" name='remove' value="-" /><br><br>
</table>
</div>
</div>
<br>
</div>
</div>
I have managed to make changes as per your need, also I have used jquery as you had added into your code.
I have calculated output in the remove() you can move it to a common function to avoid dirty code.
function remove() {
var x = document.getElementById("rowrow").rows.length;
if (x == 1) {} else {
var ele = document.querySelectorAll('input.input');
let sum = 0;
ele.forEach(input => {
sum += input.value ? parseFloat(input.value) : 0;
});
sum = sum - ele[ele.length - 1].value;
document.getElementById('result').textContent = sum.toFixed(2);
document.getElementById("rowrow").deleteRow(-1);
};
}
Changed GST id to class, as id should be unique.
Added this line of code to print GST into each row.
$(input).parents("tr").find(".gst").text((input.value * 0.07).toFixed(2));
you had added 2 class attributes to input in JS template, also merged them.
<tr>
<td></td>
<td><output class="gst">0.00</output></td>
<td>
<input
type="text"
name="Amount[]"
class="columninput input" // This line
oninput="myFunction(this.value)"
placeholder="Amount"
style="font-size:14px;"
min="0" lang="en-150"
onchange="force2decimals(this)"
onkeypress="validate(event)"
inputmode="numeric"
>
</td>
</tr>
function validate(evt) {
var theEvent = evt || window.event;
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode(key);
var regex = /[0-9]|\./;
if (!regex.test(key)) {
theEvent.returnValue = false;
if (theEvent.preventDefault) theEvent.preventDefault();
}
}
function force2decimals(event) {
var value = $(event).val();
var format_val = parseFloat(value).toFixed(2);
$(event).val(format_val);
}
//<----------------------2 Decimal force END-------------------->
// +
function mFunction() {
document.getElementById("rowrow").insertRow(-1).innerHTML =
'<tr><td></td><td><output class="gst">0.00</output></td><td><input type="text" name="Amount[]" class="columninput input" oninput="myFunction(this.value)" placeholder="Amount" style="font-size:14px;" min="0" lang="en-150" onchange="force2decimals(this)" onkeypress="validate(event)" inputmode="numeric"></td></tr>';
}
// -
function remove() {
var x = document.getElementById("rowrow").rows.length;
if (x == 1) {} else {
var ele = document.querySelectorAll('input.input');
let sum = 0;
ele.forEach(input => {
sum += input.value ? parseFloat(input.value) : 0;
});
sum = sum - ele[ele.length - 1].value;
document.getElementById('result').textContent = sum.toFixed(2);
document.getElementById("rowrow").deleteRow(-1);
};
}
function myFunction() {
debugger
var ele = document.querySelectorAll('input.input');
let sum = 0;
ele.forEach(input => {
sum += input.value ? parseFloat(input.value) : 0;
$(input).parents("tr").find(".gst").text((input.value * 0.07).toFixed(2));
});
document.getElementById('result').textContent = sum.toFixed(2);
//document.getElementById('gst').textContent = (sum * 0.07).toFixed(2);
}
.css-serial {
counter-reset: serial-number;
}
.css-serial td:first-child:before {
counter-increment: serial-number;
content: counter(serial-number);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container">
<div id="body">
<br>
<div class="row">
<div class="css-serial" style="overflow-x:auto;">
<table id="rowrow">
<tr>
<td id="number"></td>
<td><output class="gst">0.00</output></td>
<td><input type="text" name="Amount[]" class="input" oninput="myFunction(this.value)" id="columninput" placeholder="Amount" style="font-size:14px;" min="0" lang="en-150" onchange="force2decimals(this)" onkeypress='validate(event)' inputmode='numeric'
required></td>
Total Amount <output id="result"> 0.00 </output>
<input type="button" id="slipbutton1" onclick="mFunction();" name='add' value="+" />
<input type="button" id="slipbutton2" onclick="remove();" name='remove' value="-" /><br><br>
</table>
</div>
</div>
<br>
</div>
</div>
I know that + is used for both addition and concatenation, it depends on what the variable type is. I have tried using Number() and parseFloat(), but I can't seem to get them to work. Here is my code:
var grandtotal;
$("#table tr").each(function () {
var row = $(this).closest('tr');
var totalprice = row.find('input[id^="TotalPrice"]').val();
grandtotal += totalprice;
});
$(".total_price").html(grandtotal);
This code gives me an output like this:
NaN1081083936354412531.5105
However, if I add Number() or parseFloat() to the totalprice line like this:
grandtotal += Number(totalprice);
OR
grandtotal += parseFloat(totalprice);
I get nothing returned.
Anybody have any idea what I need to change? Thank you.
EDIT: I have changed the controller code to this:
var grandtotal = 0;
$("#table tr").each(function () {
var row = $(this).closest('tr');
var totalprice = parseFloat(row.find('input[id^="TotalPrice"]').val());
grandtotal += totalprice;
});
$(".total_price").html(grandtotal);
Here is the HTML in question:
<td>
<div class="input-group"> <div class="input-group-addon">$ </div>
<input readonly="readonly" readonly id="TotalPrice{{ $loop->iteration }}" name="TotalPrice[]" placeholder="" class="form-control input-md" step="0.01" type="number" value="{{ $item->TotalPrice }}">
</div>
</td>
I am still getting a blank output.
Making grandtotal to 0 with parseFloat() will solve your problem. You are trying to add tr values to undefined variable.
// give grand total a value
var grandtotal = 0;
$(document).ready(function(){
$("#table tr").each(function () {
var row = $(this).closest('tr');
var totalprice = parseFloat(row.find('input[id^="TotalPrice"]').val());
grandtotal += totalprice;
});
$(".total_price").html(grandtotal);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="table">
<tr>
<td>
<input type="text" id="TotalPrice" value="1000.50"/>
</td>
</tr>
<tr>
<td>
<input type="text" id="TotalPrice" value="2000"/>
</td>
</tr>
<tr>
<td>
<input type="text" id="TotalPrice" value="10"/>
</td>
</tr>
</table>
<div class="total_price"></div>
Try checking isNaN:
// Inside each
if (totalprice && totalprice.length > 0 && !isNaN(totalprice)) {
grandtotal += parseFloat(totalprice);
}
function getFloat(val) {
if (val && val.length > 0 && !isNaN(val)) {
return parseFloat(val);
}
return null;
}
console.log("getFloat($('#inp1').val()): " + getFloat($('#inp1').val()));
console.log("getFloat($('#inp2').val()): " + getFloat($('#inp2').val()));
console.log("getFloat($('#inp3').val()): " + getFloat($('#inp3').val()));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="inp1" type="text" value="" />
<input id="inp2" type="text" value="literal" />
<input id="inp3" type="text" value="100" />
I want to sum the value of dynamically created textbox, but it doesn't work.
$(document).ready(function() {
//iterate through each textboxes and add keyup
//handler to trigger sum event
$(".code").each(function() {
$(this).keyup(function() {
calculateSum();
});
});
});
function calculateSum() {
var sum = 0;
//iterate through each textboxes and add the values
$(".code").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 addrow() {
$("#customFields").append('<tr><td><input type="text" class="ename" id="name" placeholder="Expense Name"/> </td> <td><input type="text" class="code" id="code" placeholder="Amount"/> </td> </tr>');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="customFields">
<tr>
<td>
<input type="button" value="Add" onclick="addrow();" />
</td>
</tr>
</table>
You should use .on() on the table, which allows interaction with new dynamically-created elements. This will allow all keyup from all .code (even those added after page load) to bubble up to #customFields. The rest of your code should not need to be altered.
$(document).ready(function() {
$("#customFields").on( "keyup", ".code", function(){
calculateSum();
});
});
http://api.jquery.com/on/
Please see the
Running Code
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
//iterate through each textboxes and add keyup
//handler to trigger sum event
$(".code").each(function() {
$(this).keyup(function() {
calculateSum();
});
});
});
function calculateSum() {
var sum = 0;
//iterate through each textboxes and add the values
$(".code").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 addrow() {
$("#customFields").append('<tr><td><input type="text" class="ename" id="name" placeholder="Expense Name"/> </td> <td><input type="text" class="code" id="code" placeholder="Amount" onKeyUp = "calculateSum()"/> </td> </tr>');
}
</script>
</head>
<body>
<table id="customFields">
<tr>
<td colspan ="2">
<input type="button" value="Add" onclick="addrow();" />
</td>
</tr>
<tr><td><div id="sum">value</div></td></tr>
</table>
</body>
</html>
I'm a bit stuck with javascript again. Basically when you click a button a new row of fields will appear, giving them a new name just a different number.
I now need these fields to be able to auto sum by themself, i can do this with the first row I just don't know how to do them with the new generated ones.
The Javascript code:
<script language="javascript" type="text/javascript">
var i=2;
function addRow()
{
var tbl = document.getElementById('customersAdd');
var lastRow = tbl.rows.length;
var iteration = lastRow - 1;
var row = tbl.insertRow(lastRow);
var firstCell = row.insertCell(0);
var el = document.createElement('input');
el.placeholder = 'Quantity';
el.type = 'text';
el.name = 'quantity' + i;
el.id = 'quantity' + i;
firstCell.appendChild(el);
var secondCell = row.insertCell(1);
var el2 = document.createElement('input');
el2.placeholder = 'Description';
el2.type = 'text';
el2.name = 'description' + i;
el2.id = 'description' + i;
secondCell.appendChild(el2);
var thirdCell = row.insertCell(2);
var el3 = document.createElement('input');
el3.placeholder = 'Rate';
el3.type = 'text';
el3.name = 'rate' + i;
el3.id = 'rate' + i;
thirdCell.appendChild(el3);
var forthCell = row.insertCell(3);
var el4 = document.createElement('input');
el4.placeholder = 'Amount';
el4.type = 'text';
el4.name = 'amount' + i;
el4.id = 'amount' + i;
forthCell.appendChild(el4);
// alert(i);
i++;
// alert(i);
}
function startCalc(){
interval = setInterval("calc()",1);
}
function calc(){
one = document.main.quantity1.value;
two = document.main.rate1.value;
document.main.amount1.value = (one * 1) * (two * 1);
}
function stopCalc(){
clearInterval(interval);
}
</script>
The HTML code:
<form action="submit.php" name="main" method="post">
<table style="border-collapse: collapse;" border="0" align="center" width="50%" class="horiz" id="customersAdd">
<tr>
<td align="center"><br/>
<input class="text" style="width:100%" type="button" align="middle"value="Add Aditional Row" onClick="addRow()" /></td>
</tr>
<tr align="center">
<td>
<br />
<input placeholder="Quantity" type="text" name="quantity1" id="quantity1" onFocus="startCalc();" onBlur="stopCalc();" />
<br /></td>
<td>
<br />
<input placeholder="Description" type="text" name="description1" id="description1"/>
<br /></td>
<td>
<br />
<input placeholder="Rate" type="text" name="rate1" id="rate1" onFocus="startCalc();" onBlur="stopCalc();"/>
<br /></td>
<td>
<br />
<input placeholder="Amount" type="text" name="amount1" id="amount1" onBlur="stopCalc();" onFocus="startCalc();" readonly="true" />
<br /></td>
</tr>
</table></form>
To make things easier for anyone who could help me I have made this in JSBin to see it easier of what i want to do. Any suggestions are appreciated.
http://jsbin.com/atabaz/1/edit
Thanks
In the end I managed to find a way on how to do this myself, if anyone is interested take a look at this:
http://jsfiddle.net/2sYgE/
var currentItem = 1;
$('#customersAdd').on('keyup', '.quantity, .rate, .amount', calculateRow);
$('#addnew').click(function() {
currentItem++;
$('#customersAdd').append('<tr><td><input placeholder="Quantity" type="text" name="quantity' + currentItem +'" id="quantity' + currentItem +'" class="qty form-input-rate" /></td><td><input placeholder="Description" type="text" name="description' + currentItem +'" id="description' + currentItem +'" class="form-input-rate"/></td><td><input placeholder="Rate" type="text" name="rate' + currentItem +'" id="rate' + currentItem +'" class="rate form-input-rate"/></td><td><input placeholder="Amount" type="text" name="amount' + currentItem +'" id="amount' + currentItem +'" class="cal form-input-rate"/></td></tr>'
);
});
function calculateSum() {
var sum = 0;
$(".cal").each(function () {
if (!isNaN(this.value) && this.value.length != 0) {
sum += parseFloat(this.value);
}
});
}
function calculateRow() {
var cost = 0;
var $row = $(this).closest("tr");
var qty = parseFloat($row.find('.qty').val());
// changed the following line to only look within the current row
var rate = parseFloat($row.find('.rate').val());
cost = qty * rate;
if (isNaN(cost)) {
$row.find('.cal').val("0");
} else {
$row.find('.cal').val(cost);
}
calculateSum();
}
Polling for changes is a very inefficient and error–prone way to do form updates. Listening for change events is a better way to go as it uses fewer resources and waits until the user has finished updating the control before doing anything. There is also an input event that can be used, but it's not suitable here as it will update the form as the user enters values. Much better to wait for the user to finish entering values, then do the update.
I've re–factored your code below, it's not ready for production but it should give you some idea of how to go about it. Table rows are cloned as it's much faster than creating all the elements from scratch. Then names are modified, though this isn't really necessary. There is no need for ID attributes.
Cloning only works reliably here if inline listeners are used on the form controls. If the initial listeners are dynamically attached, you'll have to add them each time a row is added as listeners added using addEventListener are not cloned.
I haven't included any input validation, if the user puts in junk, they get junk back. You should validate input to check that appropriate values are being entered, and also format the displayed values for presentation.
<script type="text/javascript">
function addRow(element) {
var form = element.form;
var table = form.getElementsByTagName('table')[0];
var tbody = table.tBodies[0];
var num = tbody.rows.length - 1;
var row = table.rows[1].cloneNode(true);
var input, inputs = row.getElementsByTagName('input')
// Update input names
for (var i=0, iLen=inputs.length; i<iLen; i++) {
input = inputs[i];
input.name = input.name.replace(/\d+$/,num);
input.value = '';
}
tbody.insertBefore(row, tbody.rows[tbody.rows.length - 1]);
}
function updateRow(element) {
var form = element.form;
var num = element.name.replace(/^\D+/,'');
var value = form['quantity' + num].value * form['rate' + num].value;
form['amount' + num].value = (value == 0)? '' : value;
updateTotal(form);
}
function updateTotal(form) {
var elements = form.elements;
var name = /^amount/;
var total = 0;
var value;
for (var i=0, iLen=elements.length; i<iLen; i++) {
if (name.test(elements[i].name)) {
total += parseFloat(elements[i].value);
}
}
form.total.value = total;
}
</script>
<form action="submit.php" name="main" method="post">
<table style="border-collapse: collapse;" border="0" align="center"
width="50%" class="horiz" id="customersAdd">
<tr>
<td><br>
<input class="text" style="width:100%" type="button"
align="middle"value="Add Aditional Row" onclick="addRow(this)">
</td>
</tr>
<tr>
<td>
<input placeholder="Quantity" name="quantity1" onblur="updateRow(this);">
</td>
<td>
<input placeholder="Description" type="text" name="description1">
</td>
<td>
<input placeholder="Rate" name="rate1" onchange="updateRow(this);">
</td>
<td>
<input placeholder="Amount" name="amount1" readonly>
</td>
</tr>
<tr>
<td colspan="3" style="text-align: right">Total
<td><input name="total" readonly>
</tr>
</table>
<input type="reset">
</form>