Calculate values from multiple number fileds - Jquery - javascript

I am trying to calculate price based on quantity and price and calculating a subtotal by adding all products prices.
below is the code of html
<tr>
<td>
<input min="0" data-unit-price="9.99" class="se-ticket-qty" type="number" value="0" />
</td>
</tr>
<tr>
<td>
<input min="0" data-unit-price="19.99" class="se-ticket-qty" type="number" value="0" />
</td>
</tr>
<tr>
<td>
<h3><span class="se-curency">$</span><span data-sub-total="0" id="se-sub-total" class="se-total-amount">0</span></h3>
<h3><span class="se-curency">$</span><span id="se-vat" class="se-total-amount">8</span></h3>
</td>
</tr>
And I am trying The below js
jQuery( document ).on( 'input', '.se-ticket-qty', function() {
var sum = 0;
jQuery(this).each(function(i){
var unit_price = jQuery(this).data('unit-price');
var amount = jQuery(this).val();
var current_sub_total = parseFloat(unit_price);
sum += current_sub_total;
var sub_total = jQuery('#se-sub-total').attr('data-sub-total');
var final_sub_total = parseFloat(sub_total) + sum;
jQuery('#se-sub-total').attr('data-sub-total', final_sub_total.toFixed(2));
jQuery('#se-sub-total').html(final_sub_total.toFixed(2));
});
console.log(sum);
});
But There is an error in calculating.The sub total is working fine if I use upper arrow in number field.But if i use below arrow or input an number by manually it is not working.

It looks like you just had a few small issues with how you were using each logic and adding up the totals. Here is a snippet that does what I think you were trying to do. Just un-comment the console.logs to see how the order of operations changed how the final sum is calculated. I am not sure what you wanted with the second display with 8$:
// Shorthand for $( document ).ready()
$(function() {
console.log( "ready!" );
$(document).on('input', '.se-ticket-qty', function(){
CalculateTotal();
});
});
function CalculateTotal(){
var sum = 0;
$(".tableWithInputs").find( ".se-ticket-qty" ).each(function( index ){
var unit_price = parseFloat($(this).data('unit-price'));
var amount = parseFloat($(this).val());
var totalPrice = unit_price * amount;
//console.log("unit_price: " + unit_price);
//console.log("unit_price: " + unit_price);
//console.log("amount: " + amount);
//console.log("totalPrice: " + totalPrice);
sum += parseFloat(totalPrice);
});
$('#se-sub-total').attr('data-sub-total', sum.toFixed(2));
$('#se-sub-total').text(sum.toFixed(2));
//console.log(sum.toFixed(2));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="tableWithInputs">
<tr>
<td>
<input min="0" data-unit-price="9.99" class="se-ticket-qty" type="number" value="0" />
</td>
</tr>
<tr>
<td>
<input min="0" data-unit-price="19.99" class="se-ticket-qty" type="number" value="0" />
</td>
</tr>
<tr>
<td>
<h3><span class="se-curency">$</span><span data-sub-total="0" id="se-sub-total" class="se-total-amount">0</span></h3>
<h3><span class="se-curency">$</span><span id="se-vat" class="se-total-amount">8</span></h3>
</td>
</tr>
</table>

Related

Rewriting JavaScript code with consequent numbers in the names of ids

I'm trying to apply a function to input field with ids that contain consequent numbers (ie. price1, price2, price3), etc.
There's no problem with the first row of field that are defined for a start. But further input fields are dynamically added by a jQuery function and their number is not known in advance.
I hoped it would be an easy loop to apply:
var i=1;
$("#quantity"+i).keyup(function() {
var price= $("#price"+i).val();
var quantity= $(this).val();
var value= price*quantity;
var value=value.toFixed(2); /* rounding the value to two digits after period */
value=value.toString().replace(/\./g, ',') /* converting periods to commas */
$("#value"+i).val(value);
});
So far so good - the outcome of the multiplication properly displays in the id="value1" field after the "quantity" field is filled up.
Now further fields should follow the pattern and calculate the value when the quantity is entered - like this:
[price2] * [quantity2] = [value2]
[price3] * [quantity3] = [value3]
etc.
So the code follows:
$('#add_field').click(function(){ /* do the math after another row of fields is added */
var allfields=$('[id^="quantity"]');
var limit=(allfields.length); /* count all fields where id starts with "quantity" - for the loop */
for (var count = 2; count < limit; count++) { /* starting value is now 2 */
$("#quantity"+count).keyup(function() {
var cena = $("#price"+count).val();
var quantity= $("#quantity"+count).val();
var value= price*quantity;
var value=value.toFixed(2);
value=value.toString().replace(/\./g, ',')
$("#value"+count).val(value);
});
}
});
The problem is that all further "value" fields are only calculated when "quantity2" is (re)entered and the "value2" is not calculated at all.
I guess there's a mistake while addressing fields and/or triggering the calculation.
How should I correct the code?
Just in case the "add_field" function is needed to solve the problem:
$(document).ready(function(){
var i=1;
$('#add_field').click(function(){
i++;
$('#offer').append('<tr id="row'+i+'">
<td><input type="text" name="prod_num[]" id="prod_num'+i+'" placeholder="Product number (6 digits)"></td><td><input type="text" name="prod_name[]" disabled></td>
<td><input type="text" name="cena[]" id="price'+i+'" placeholder="Enter your price"></td>
<td><input type="text" name="quantity[]" id="quantity'+i+'" placeholder="Enter quantity"></td>
<td><input type="text" name="value[]" id="value'+i+'" disabled></td>
<td><button type="button" name="remove_field" id="'+i+'" class="button_remove">X</button></td></tr>');
});
Incrementing IDs is a lot more trouble than it is worth, especially when you start removing rows as well as adding them.
This can all be done using common classes and traversing within the specific row instance.
To account for future rows use event delegation.
Simplified example:
// store a row copy on page load
const $storedRow = $('#myTable tr').first().clone()
// delegate event listener to permanent ancestor
$('#myTable').on('input', '.qty, .price', function(){
const $row = $(this).closest('tr'),
price = $row.find('.price').val(),
qty = $row.find('.qty').val();
$row.find('.total').val(price*qty)
});
$('button').click(function(){
// insert a copy of the stored row
// delegated events will work seamlessly on new rows also
const $newRow = $storedRow.clone();
const prodName = 'Product XYZ';// get real value from user input
$newRow.find('.prod-name').text(prodName)//
$('#myTable').append($newRow)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>Add row</button>
<table id="myTable">
<tr>
<td class="prod-name">Product 1</td>
<td>Qty:<input type="number" class="qty" value="0"></td>
<td>Price:<input type="number" class="price" value="0"></td>
<td>Total:<input type="text" class="total" value="0" readonly></td>
</tr>
<tr>
<td class="prod-name">Product 2</td>
<td>Qty:<input type="number" class="qty" value="0"></td>
<td>Price:<input type="number" class="price" value="0"></td>
<td>Total:<input type="text" class="total" value="0" readonly></td>
</tr>
</table>
Understanding Event Delegation
The first thing to consider is that you can get the length of a selector. So for example:
var count = $("input").length;
If there is one, value here would be 1. if there are four, the value would be 4.
You can also use .each() option to itereate each of the items in the selector.
$('#add_field').click(function(){
var allFields = $('[id^="quantity"]');
allFields.each(function(i, el){
var c = i + 1;
$(el).keyup(function() {
var price = parseFloat($("#price" + c).val());
var quantity = parseInt($(el).val());
var value = price * quantity;
value = value.toFixed(2);
value = value.toString().replace(/\./g, ',');
$("#value" + c).val(value);
});
});
});
You could also create relationship based on the ID itself.
$(function() {
function calcTotal(price, qnty) {
return (parseFloat(price) * parseInt(qnty)).toFixed(2);
}
$('#add_field').click(function() {
var rowClone = $("#row-1").clone(true);
var c = $("tbody tr[id^='row']").length + 1;
rowClone.attr("id", "row-" + c);
$("input:eq(0)", rowClone).val("").attr("id", "prod_num-" + c);
$("input:eq(1)", rowClone).val("").attr("id", "price-" + c);
$("input:eq(2)", rowClone).val("").attr("id", "quantity-" + c);
$("input:eq(3)", rowClone).val("").attr("id", "value-" + c);
$("button", rowClone).attr("id", "remove-" + c);
rowClone.appendTo("table tbody");
});
$("table tbody").on("keyup", "[id^='quantity']", function(e) {
var $self = $(this);
var id = $self.attr("id").substr(-1);
if ($("#price-" + id).val() != "" && $self.val() != "") {
$("#value-" + id).val(calcTotal($("#price-" + id).val(), $self.val()));
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="add_field">Add Field</button>
<br />
<h2>Product</h2>
<table>
<thead>
<tr>
<td>Number</td>
<td>Name</td>
<td>Price</td>
<td>Quantity</td>
<td>Total</td>
<td></td>
</thead>
<tbody>
<tr id="row-1">
<td><input type="text" name="prod_num[]" id="prod_num-1" placeholder="Product number (6 digits)"></td>
<td><input type="text" name="prod_name[]" disabled></td>
<td><input type="text" name="cena[]" id="price-1" placeholder="Enter your price"></td>
<td><input type="text" name="quantity[]" id="quantity-1" placeholder="Enter quantity"></td>
<td><input type="text" name="value[]" id="value-1" disabled></td>
<td><button type="button" name="remove_field" id="remove-1" class="button_remove">X</button></td>
</tr>
</tbody>
</table>

How to get values to the outside from three functions and update them in real time?

I have a table which lets users to add number of participants for an event. in it I used input type number field to get number of participants. then I calculate how much fee they have to pay for each passenger type. I have 3 passenger types.
My table looks like this,
I use keyup mouseup bind to get the input value by user and multiplied it with fee for one participant.
var totalAdults;
jQuery("#number_adults").bind('keyup mouseup', function () {
var numOfAdults = jQuery("#number_adults").val();
totalAdults = numOfAdults * adultFee;
});
I have 3 of above functions to calculate and real time display how much fee that they have to pay in each passenger type.
Now I need to get the total sum of all three passenger type fees and display/update it in real time to the user, at the end of my table.
I tried making each passenger type total value global and calculating it's sum, but I get an error saying missing semicolon error linked to this MDN article
I'm stuck here. how can I get total value on all three passenger types outside their respective functions and display that value correctly in real time? (when they update number of passengers, total for passenger type is changing, I need to change final total accordingly). please help
Update:
this is the html table that I used. this get repeated another two times for other two passenger types.
var adultFee = 150;
var finalTotal = 0;
jQuery("#number_adults").bind('keyup mouseup', function() {
var numOfAdults = jQuery("#number_adults").val();
totalAdults = numOfAdults * adultFee;
jQuery("#adult_amount").html(totalAdults);
// console.log(totalAdults);
finalTotal = finalTotal + totalAdults;
console.log(finalTotal);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<tr>
<td style="font-weight: 600;">Adult</td>
<td id="adult_price" name="adult_price">150.00</td>
<td>
<input id="number_adults" max="3" min="1" name="number_adults" type="number" value="0" class="form-control">
</td>
<td name="amount">
<p id="adult_amount"></p>
</td>
</tr>
This is how I tried to get the final total, it doesn't display any result
jQuery(document).on('change', '#adult_amount', function() {
finalTotal = finalTotal+totalAdults;
alert(finalTotal);
});
I made a working example for you.
$('.inputs').each(function(){
$(this).on('change keyup', function(){
let sumTotal = 0;
$('.inputs').each(function(){
sumTotal += $(this).val() * +$(this).parent().next().data('price');
});
$('.total').text(`${sumTotal} $`);
});
});
td:nth-child(3),
th:nth-child(3){
text-align:center;
}
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
<body>
<div class="container">
<div class="row justify-content-center">
<div class="col-12">
<table class="table table-hover">
<thead>
<tr>
<th></th>
<th>QTY</th>
<th>Amount</th>
</tr>
</thead>
<tbody>
<tr>
<td>Child</td>
<td><input type="number" class="inputs form-control" value="0" min="0" max="999"></td>
<td class="price" data-price="150">150 $</td>
</tr>
<tr>
<td>Adult</td>
<td><input type="number" class="inputs form-control" value="0" min="0" max="999"></td>
<td class="price" data-price="200">200 $</td>
</tr>
<tr>
<td>Adult Plus</td>
<td><input type="number" class="inputs form-control" value="0" min="0" max="999"></td>
<td class="price" data-price="250">250 $</td>
</tr>
<tr>
<td>Total - </td>
<td></td>
<td class="total">0.00 $</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</body>
</html>
(https://codepen.io/bichiko/pen/JQWomy)
Here is a solution which should do what you need.
Compared to your code, the key changes are:
Use classes instead of IDs to identify the elements within each row. This means you can handle changes to all your fields using the same event handling code. I've given all your quantity fields the .qty class, and then bound the event to that class, so all elements with that class will run the same function.
Within the function, I've stripped out all direct references to fields - instead, to get the price field, and the total field for the relevant type, the code uses the positions of the fields relative to each other in the page, it uses the .parent(), .next(), and .prev() functions to find the total and amount fields which are within the same table row as the altered quantity field (which will always be this inside the event handler), so that it does the calculations on the right fields.
To calculate the final overall total, I've defined a separate function. Again this uses a class selector to identify all the "amount" fields, and add each of those values together to get the total. Since this function is triggered at the end of the event handler, it will always update the grand total whenever one of the quantities is updated.
Other minor changes:
use .on() instead of the deprecated .bind()
jQuery(".qty").on('keyup mouseup', function() {
var tdElement = jQuery(this).parent();
var qty = parseInt(this.value);
var fee = parseFloat(tdElement.prev(".price").text());
var typeTotal = qty * fee;
tdElement.next(".amount").html(typeTotal);
calcFinalTotal();
});
function calcFinalTotal()
{
var finalTotal = 0;
$(".amount").each(function() {
finalTotal += parseFloat($(this).text());
});
$("#total").text(finalTotal);
}
td, th
{
border: solid 1px #cccccc;
padding: 5px;
text-align:left;
}
table {
border-collapse: collapse;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<th>Passenger Type</th>
<th>Price</th>
<th>Quantity</th>
<th>Total</th>
<tr>
<th>Adult</th>
<td class="price">150.00</td>
<td>
<input max="3" min="1" name="number_adults" type="number" value="0" class="form-control qty">
</td>
<td class="amount">0
</td>
</tr>
<tr>
<th>Type 2</th>
<td class="price" id="type3_price">200.00</td>
<td>
<input max="3" min="1" name="number_type" type="number" value="0" class="form-control qty">
</td>
<td class="amount">0
</td>
</tr>
<tr>
<th>Type 3</th>
<td class="price" id="type3_price">200.00</td>
<td>
<input max="3" min="1" name="number_type" type="number" value="0" class="form-control qty">
</td>
<td class="amount">0
</td>
</tr>
<tr>
<th colspan="3">Grand Total</th>
<td id="total"></td>
</tr>
</table>
You can simply loop on every rows on the table and calculate the total sum and also the individual. Here i done by the dynamic method. if the total of each passenger is inserted in a unique input, then you can access from that input. Otherwise please follow the method
$(document).on('keyup mouseup','.qty', function() {
calculate();
});
function calculate(){
var finalTotal = 0;
var old = 0;
var mature = 0;
var adult = 0;
$('.qty').each(function(key,value){
$qty = $(this).val();
$type = $(this).attr('data-type');
$amount = $(this).parent().siblings('.adult_price').html();
$total = Number($qty) * parseFloat($amount);
$(this).parent().siblings('.amount').html($total);
finalTotal += $total;
if($type == 'adult')
adult += parseFloat($total);
else if($type == 'mature')
mature += parseFloat($total);
else if($type == 'old')
old += parseFloat($total);
});
$('.grandTotal').html(finalTotal);
// console.log('Adult',adult);
// console.log('Mature',mature);
// console.log('Old',old);
}
table {
border-collapse: collapse;
width: 80%;
}
th, td {
text-align: left;
padding: 8px;
}
tr:nth-child(even){background-color: #f2f2f2}
th {
background-color: #4CAF50;
color: white;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<thead>
<tr>
<th>Passenger Types</th>
<th>Amount</th>
<th>Qty</th>
<th>Total</th>
</tr>
</thead>
<tbody>
<tr>
<td><b>Adult</b></td>
<td class="adult_price" name="adult_price">150.00</td>
<td>
<input max="3" min="1" name="number_adults" type="number" value="0" class="form-control qty" data-type="adult">
</td>
<td name="amount" class='amount'></td>
</tr>
<tr>
<td><b>Mature</b></td>
<td class="adult_price" name="adult_price">200.50</td>
<td>
<input max="3" min="1" name="number_adults" type="number" value="0" class="form-control qty" data-type="mature">
</td>
<td name="amount" class='amount'></td>
</tr>
<tr>
<td><b>Old</b></td>
<td class="adult_price" name="adult_price">150.00</td>
<td>
<input max="3" min="1" name="number_adults" type="number" value="0" class="form-control qty" data-type="old">
</td>
<td name="amount" class='amount'></td>
</tr>
<tr>
<td colspan="3"><b>Grand Total</b></td>
<td class='grandTotal'>100</td>
</tr>
</tbody>
</table>
jQuery is very flexible use class instead of id. If you use inputs, selects, etc you should delegate the input or change event to them.
$('input').on('input', function() {...
input event will trigger as soon as user types or selects on or to an input tag. change event will trigger when a user types or selects on or to an input and then clicks (unfocus or blur event) elsewhere.
The HTML is slightly modified for consistency. Note that there are 2 extra inputs per <tr>.
When using input inside tables you can traverse the DOM by first referencing the imputed/changed/clicked tag as $(this) then climb up to the parent <td> and from there either go to the next <td> using .next() or go to the previous <td> using .prev(). Once you get to a neighboring <td> use .find() to get the input within. When extracting a number from an input it is normally a string but with jQuery method .val() it should extract input value as a number automatically. Details commented in demo.
/*
//A - Any tag with the class of .qty that the user inputs data into triggers a function
//B - Get the value of the imputed .qty (ie $(this))
//C - reference $(this) parent <td> go to the next <td> then find a tag with the class .price and get its value
//D - reference $(this) parent <td> go to the previous <td> then find a tag with the class of .total then set its value to the product of qty and price and fix it with hundredths (.00 suffix)
//E - Declare an empty array
//F - Get the value of each .total, convert it into a number then push the number into the empty array
//G - Use .reduce() to get the sum of all values within the array then fix it with hundredths (.00 suffix) and set it as the value of .grand
*/
$('.qty').on('input', function() { //A
var qty = $(this).val(); //B
var price = $(this).parent().prev('td').find('.price').val(); //C
$(this).parent().next('td').find('.total').val((qty * price).toFixed(2)); //D
var totals = []; //E
$('.total').each(function() {
totals.push(Number($(this).val()));
}); //F
$('.grand').val(totals.reduce((sum, cur) => sum + cur).toFixed(2)); //G
});
table {
table-layout: fixed;
}
td {
width: 6ch
}
[readonly] {
border: 0;
width: 6ch;
text-align: right
}
[type=number] {
text-align: right
}
<table>
<tr>
<td style="font-weight: 600;">Adult</td>
<td><input class="price" name='price' value='150.00' readonly></td>
<td>
<input class="qty" name="qty" min="0" max="3" type="number" value="0" class="form-control">
</td>
<td>
<input class="total" name='total' readonly>
</td>
</tr>
<tr>
<td style="font-weight: 600;">Senior</td>
<td><input class="price" name='price' value='100.00' readonly></td>
<td>
<input class="qty" name="qty" min="0" max="3" type="number" value="0" class="form-control">
</td>
<td>
<input class="total" name='total' readonly>
</td>
</tr>
<tr>
<td style="font-weight: 600;">Child</td>
<td><input class="price" name='price' value='75.00' readonly></td>
<td>
<input class="qty" name="qty" min="0" max="3" type="number" value="0">
</td>
<td>
<input class="total" name='total' readonly>
</td>
</tr>
<tr>
<td colspan='3' style='text-align:right;'>Total</td>
<td><input class='grand' name='grand' value='0' readonly></td>
</table>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
This is axample of yours problem, try using object
var data = {a:0, b:0, c: 0}
function one (){
data.a = data.a + 10
console.log(data.a)
total()
}
function two (){
data.b = data.b + 10
total()
console.log(data.b)
}
function three () {
data.c = data.c + 30
total()
console.log(data.c)
}
function total () {
var totaly = data.a + data.b + data.c
console.log('Total input :', totaly)
}
<button onclick="one()"> get A </button>
<button onclick="two()"> get B</button>
<button onclick="three()"> get C </button>

Jquery subtotal function conflicting with js gst function

O.k today is starting to be 1 step forward and 2 steps back. I have a Jquery function that does the price x qty = subtotal in the form and then each subtotal is calculated into a total, Which is all fine and dandy. I then have a plain js function that took that total value and added the gst and then a further subtotal figure which was created on it's own and works then at this point when i tried to move it over the gst and finial total functions won't work and i can't get any error codes out of it either. At this point i can only assume that the js script can't talk to the Jquery script or something is really wrong.
// Jquery script
<script type="text/javascript">
jQuery(function($) {
$(".qty, .tradeprice").change(function() {
var total = 0;
$(".qty").each(function() {
var $qty = $(this),
$row = $qty.closest('tr'),
$tradePrice = $row.find('.tradeprice'),
$subtotal = $row.find('.subtotal');
subtotal = parseInt($qty.val(), 10) * parseFloat($tradePrice.val());
total += subtotal;
$subtotal.val(subtotal);
});
$('.total').val(total);
}).change();
});
</script>
// JS script
<script type="text/javascript">
function updatePrice() {
// Get the ex-GST price from its form element
var exPrice = document.getElementById("ex-gst").value;
var gstPrice = document.getElementById("gst").value;
// Get the GST price
gstPrice = exPrice * 0.1;
var TPrice = parseInt(gstPrice) + parseInt(exPrice);
// Set the GST price in its form element
document.getElementById("gst").value = gstPrice;
document.getElementById("inc-gst").value = TPrice;
}
</script>
// bottom of HTML
<form>
<table>
<tr>
<th><input type='text' name='po101' id='po101'/></th>
<td><input name='po102' type='text' id="po102"/></td>
<td><input name='po103' type='text' id="po103" /></td>
<td>$<input name='po104' type="text" class='tradeprice' id="po104" value="0" /></td>
<th><input name='po105' type="text" class='qty' id="po105" value="0" /></th>
<td><input name='po106' type='text' class='subtotal' id="po106" readonly="true" /></td>
</tr>
<tr>
<th height='24' colspan="7">Total:<input type='text' id='Total' name='Total' class='total' readonly="true" onChange="updatePrice()"/></th>
</tr>
<tr>
<th height='24' colspan="7"><div id='submit'><input type='submit' /></div></th>
</tr>
<tr>
<th height='24' colspan="7">
<input type='text' id="gst" name='gst' onChange="updatePrice()" />
<input type='text' id="inc-gst" name='inc-gst' onChange="updatePrice(this.form)"/>
</th>
</tr>
</table>
</form>
I have now edited you code, and changed this line
var exPrice = document.getElementById("ex-gst").value;
to
var exPrice = document.getElementById("Total").value;
I have also updated the code by removing onChange() from HTML and added the trigger for your updatePrice() function to the change event.
And then this is the result (I have also added the jQuery version as comments, both will work).
jQuery(function($) {
$(".qty, .tradeprice").change(function() {
var total = 0;
$(".qty").each(function() {
var $qty = $(this),
$row = $qty.closest('tr'),
$tradePrice = $row.find('.tradeprice'),
$subtotal = $row.find('.subtotal');
subtotal = parseInt($qty.val(), 10) * parseFloat($tradePrice.val());
total += subtotal;
$subtotal.val(subtotal);
});
$('.total').val(total);
updatePrice();
}).change();
});
function updatePrice() {
// Get the ex-GST price from its form element
var exPrice = document.getElementById("Total").value;
//var exPrice = $('#Total').val() //this is jQuery
var gstPrice = document.getElementById("gst").value;
//var exPrice = $('#gst').val() //this is jQuery
// Get the GST price
gstPrice = exPrice * 0.1;
var TPrice = parseInt(gstPrice) + parseInt(exPrice);
// Set the GST price in its form element
document.getElementById("gst").value = gstPrice;
//$('#gst').val(gstPrice) //this is jQuery
document.getElementById("inc-gst").value = TPrice;
//$('#inc-gst').val(TPrice) //this is jQuery
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<table>
<tr>
<th>
<input type='text' name='po101' id='po101' />
</th>
<td>
<input name='po102' type='text' id="po102" />
</td>
<td>
<input name='po103' type='text' id="po103" />
</td>
<td>$
<input name='po104' type="text" class='tradeprice' id="po104" value="0" />
</td>
<th>
<input name='po105' type="text" class='qty' id="po105" value="0" />
</th>
<td>
<input name='po106' type='text' class='subtotal' id="po106" readonly="true" />
</td>
</tr>
<tr>
<th height='24' colspan="7">Total:
<input type='text' id='Total' name='Total' class='total' readonly="true" />
</th>
</tr>
<tr>
<th height='24' colspan="7">
<div id='submit'>
<input type='submit' />
</div>
</th>
</tr>
<tr>
<th height='24' colspan="7">
<input type='text' id="gst" name='gst' />
<input type='text' id="inc-gst" name='inc-gst' />
</th>
</tr>
</table>
</form>

Using jQuery to validate value in comparison to other input value

So I have a base Hour input field and I'm trying to validate the other input fields so that once the base hour is added the other input values can only be as large as the first base rate Hours column (first input). Or put another way the one input field becomes the max number value once it is entered. So if the base is 12 for the Hours column the second and third rate can be no larger than 12. The tricky part is add new row feature means all new rows for the hour column have to adhere to the rule as well. I have been trying to figure it out for a bit, any help would be appreciated.
Here is the fiddle: http://jsfiddle.net/uuzhuom9/
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$(document).ready(function () {
$('#calculate').on('click', function() {
$('.hours-table tr').each(function() {
var hours = $(this).find('input.hours').val();
var rate = $(this).find('input.rate').val();
var dateTotal = (hours * rate);
$(this).find('input.date-total').val(dateTotal);
// total += parseInt($("input.date-total").val());
var sum = 0;
//iterate through each textboxes and add the values
$("input.date-total").each(function () {
//add only if the value is number
if (!isNaN($(this).val()) && $(this).val().length != 0) {
sum += parseFloat(this.value);
}
});
if (sum < 0) {
alert("Total can't be negative");
$('#grandtotal-new').val('');
} else {
$("#grandtotal-new").val(sum)
}
}); //END .each
return false;
}); // END click
});
$(function(){
var counter = 4;
$('a.add-row').click(function(event){
event.preventDefault();
counter++;
var newRow = jQuery('<tr><td><input type="text" value="" /></td><td><input type="text" class="hours" name="rate-0' + counter + '"/></td><td><input type="text" class="rate" name="rate-0' + counter + '"/></td><td><input type="text" class="date-total" readonly name="date-total-0' + counter + '"/></td></tr>');
$('table.hours-table').append(newRow);
});
});
</script>
The html is:
<table class="hours-table">
<tr>
<th>Item</th>
<th>Hours</th>
<th>Hourly Rate</th>
<th>Total</th>
</tr>
<tr>
<td>Base Rate:</td>
<td class="hours"><input type="number" class="hours" id="base-hours" name="hours-01" max="???" min="???" value="" /></td>
<td class="rate"><input min="0" class="rate" name="rate-01" value="200" readonly /></td>
<td class="date-total"><input type="text" class="date-total" name="date-total-0" readonly /></td>
</tr>
<tr>
<td>Second Rate:</td>
<td class="hours"><input type="number" class="hours" name="hours-02" max="???" min="???" value="" /></td>
<td class="rate"><input type="text" class="rate" name="rate-02" value="-20" readonly /></td>
<td class="date-total"><input type="text" class="date-total" name="date-total-1" readonly /></td>
</tr>
<tr>
<td>Third Rate:</td>
<td class="hours"><input type="number" class="hours" name="hours-03" max="???" min="???" value="" /></td>
<td class="rate"><input type="text" class="rate" name="rate-03" value="10" readonly /></td>
<td class="date-total"><input type="text" class="date-total" name="date-total-2" readonly/></td>
</tr>
</table>
Add New Rule<br />
<button type="button" id='calculate' class="btn btn-inverse btn- mini">Calculate</button>
The Grand total is: <input type="number" id='grandtotal-new' min="???"/>
Just validate them on blur of each .hours input as below:
DEMO
$(document).on('blur','.hours',function(){
var current=$(this);
if(!(current).is('input.hours:first'))
{
if(current.val()>$('input.hours:first').val())
current.val('');
}
});
This will check value of input on blur and clears it if it is greater than first one
UPDATE:
DEMO
parse the value before checking as below:
$(document).on('blur','.hours',function(){
var current=$(this);
if(!(current).is('input.hours:first'))
{
if(parseInt(current.val())>parseInt($('input.hours:first').val()))
current.val('');
}
});
UPDATE 2
Based on OPs comments here is the way to achieve the requirements mentioned by him.
DEMO
$(document).on('blur','.hours',function(e){
var current=$(this);
var base=$('input.hours:first');
var total=0;
var other=$('input.hours:not(:first)');
if(base.val()==="")
{
alert('Enter Base First');
current.val('');
base.focus();
e.stopPropagation();
return;
}
$.each($(other),function(index,value){
if(value.value!=="")
total+=parseInt(parseInt(value.value));
});
console.log(total);
if(!(current).is(base))
{
if(parseInt(current.val())>parseInt(base.val()))
{
current.val('');
}
else if(total>parseInt($('input.hours:first').val()))
current.val('');
}
});
add this at the beginning of your jquery script.
this will limit the other hours input to whatever is on base-hours, including newly added rows.
var baseRate = 0;
$(".hours-table").on("input","input.hours",function() {
if ($(this).attr('id') == 'base-hours'){
baseRate = $(this).val();
}else if ($(this).val() > baseRate){
$(this).val(baseRate);
}
});
and then further down below you have a syntax/logic error on your add row function. replace this line with this corrected line, and you might wanna move your counter++ after this line.
var newRow = jQuery('<tr><td><input type="text" value="" /></td><td><input type="text" class="hours" name="rate-0' + counter + '"/></td><td><input type="text" class="rate" name="rate-0' + counter + '"/></td><td><input type="text" class="date-total" readonly name="date-total-0' + counter + '"/></td></tr>');
check this jsfiddle - http://jsfiddle.net/uuzhuom9/8/

Wrong Output by sum Floatnumber in jQuery / Javascript

I have a problem. I am trying to sum two float values with jQuery.
<tr id='idList'>
<td class="price" value="2,50">Testsum</td>
<td class="price" value="13,50">Testsum</td>
<td> <input type="text" id="total_price" readonly></td>
</tr>
And my JavaScript:
var sum = 0;
$('.price').each(function(){
sum = $(this).attr('value') + sum;
});
alert(sum);
$('#total_price').val(sum);
I got this output in my text field: 2,5013,50. Why? I cant understand, why doesn't it sum together the two values like: 2,50 + 13,50 = 16,00?
Try using parseInt() function
var sum = 0;
$('.price').each(function(){
sum = parseInt($(this).attr('value')) + sum;
});
alert(sum);
$('#total_price').val(sum);
Check Manual
You are using a string concatenation
var sum = 0;
$('.price').each(function() {
sum += (+$(this).attr('value').replace(',', '.') || 0);
});
$('#total_price').val(sum);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
<tr id='idList'>
<td class="price" value="2,50">Testsum</td>
<td class="price" value="13,50">Testsum</td>
<td>
<input type="text" id="total_price" readonly>
</td>
</tr>
</table>

Categories

Resources