Using one script to process multiple calculations from form inputs - javascript

I have a jQuery function that calculates numbers from user inputs and outputs the result in a new readonly input. The code below shows the script I'm using, but the form is just for illustration purposes because the real form has 12 or more of these inputs. My questions is, is there a way to make my one script do all calculations for all the different inputs? Or, do I have to write out 12 or more of these scripts for each set?
<html>
<head>
<script type='text/javascript' src='http://code.jquery.com/jquery-1.7.1.js'></script>
<script type='text/javascript'>//<![CDATA[
$(window).load(function(){
$(':input').bind('keypress keydown keyup change',function(){
var pp_result = parseFloat($(':input[name="pp_month_result"]').val(),10),
pp_goal = parseFloat($(':input[name="pp_month_goal"]').val(),10);
var day = "<?php echo date('d'); ?>";
var monthDays = "<?php echo date('t'); ?>";
var v = '';
if (!isNaN(pp_result) && !isNaN(pp_goal)){
v = parseFloat((pp_result) / (day) * (monthDays) / (pp_goal) * 100).toFixed(0)+"%";
}
$(':input[name="pp_month_trend"]').val(v.toString());
});
});//]]>
</script>
</head>
<body>
<form>
Result 1 <input type="text" name="pp_month_result"><br>
Goal 1 <input type="text" name="pp_month_goal"><br>
Trend 1 <input type="text" name="pp_month_trend" readonly>
Result 2 <input type="text" name="aa_month_result"><br>
Goal 2 <input type="text" name="aa_month_goal"><br>
Trend 2 <input type="text" name="aa_month_trend" readonly>
</form>
</body>
<html>
The problem I did not clarify earlier is that the second set of inputs have different names so they can be posted to a separate PHP file.
<div>
<tr>
<td>POST</td>
<td>
<input type="text" name="pp_today_result" class="numbox">
</td>
<td>
<input type="text" name="pp_today_goal" class="numbox">
</td>
<td style="padding: 0 0 0 10px; border-left: 1px solid #D6D6D6;">
<input type="text" name="pp_month_result" class="numbox">
</td>
<td style="padding: 0 0 0 5px;">
<input type="text" name="pp_month_goal" class="numbox">
</td>
<td style="padding: 0 0 0 5px;">
<input type="text" name="pp_month_trend" class="numbox" readonly>
</td>
</tr>
</div>
My inputs are inside a table as show above, is this what's preventing the suggested solution from working for me?

Group the elements using a container so that you can find the related input elements easily
<form>
<div>
Result 1 <input type="text" name="pp_month_result"/><br/>
Goal 1 <input type="text" name="pp_month_goal"/><br/>
Trend 1 <input type="text" name="pp_month_trend" readonly />
</div>
<div>
Result 2 <input type="text" name="pp_month_result"/><br/>
Goal 2 <input type="text" name="pp_month_goal"/><br/>
Trend 2 <input type="text" name="pp_month_trend" readonly />
</div>
</form>
then
$(window).load(function(){
$(':input').bind('keypress keydown keyup change',function(){
var $div = $(this).closest('div');
var pp_result = parseFloat($div.find(':input[name$="_month_result"]').val(),10),
pp_goal = parseFloat($div.find(':input[name$="_month_goal"]').val(),10);
var day = 5;
var monthDays = 2;
var v = '';
if (!isNaN(pp_result) && !isNaN(pp_goal)){
v = parseFloat((pp_result) / (day) * (monthDays) / (pp_goal) * 100).toFixed(0)+"%";
}
$div.find(':input[name$="_month_trend"]').val(v.toString());
});
});
Demo: Fiddle

Related

javascript multiply 2 number show total and gtotal but show only one value?

I am using javascript calculation. multiply 2 numbers: number 1 * number 2 = total and how g-total but working only one value display?
I have need number 1 * number 2 = total and show Gtotal so please help and share a valuable idea...
HTML
<input
name="per_hour"
id="per_hour"
class="form-control"
value=""
onblur="perhour()"
placeholder="0"
/>
<input
name="per_hour_x"
id="per_hour_x"
class="form-control"
onblur="perhour()"
value=""
placeholder="0.00"
/>
Total
<input
name="per_hour_total"
id="per_hour_total"
class="form-control"
value=""
placeholder="0.00"
/>
G-Total
<input
type="text"
class="form-control total-fare"
id="total"
disabled
value="<?= $booking->total_fare ?>"
/>
<script>
function perhour() {
var per_hour = document.getElementById("per_hour").value;
var per_hour_x = document.getElementById("per_hour_x").value;
var amts = document.getElementById("total").value;
var totaperhour = Number(per_hour) * Number(per_hour_x);
var totalamt = Number(totaperhour) + Number(amts);
$("#per_hour_total").val(totaperhour).toFixed(2); //working
$("#total").val(totalamt).toFixed(2); //not working
}
</script>
It should be $('#per_hour_total').val(totaperhour.toFixed(2)); and not $('#per_hour_total').val(totaperhour).toFixed(2);
function perhour() {
var per_hour = document.getElementById("per_hour").value;
var per_hour_x = document.getElementById("per_hour_x").value;
var amts = document.getElementById("total").value;
var totaperhour = Number(per_hour) * Number(per_hour_x);
var totalamt = Number(totaperhour) + Number(amts);
$('#per_hour_total').val(totaperhour.toFixed(2));
$('#total').val(totalamt.toFixed(2));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<div>
total
<input type="text" class="form-control total-fare" disabled id="total" value="">
</div>
<div>
per_hour
<input name="per_hour" id="per_hour" class="form-control" value="" onblur="perhour()" placeholder="0">
</div>
<div>
per_hour_x
<input name="per_hour_x" id="per_hour_x" class="form-control" onblur="perhour()" value="" placeholder="0.00">
</div>
<div>
per_hour_total
<input name="per_hour_total" id="per_hour_total" class="form-control" value="" placeholder="0.00">
</div>

check input number whether bigger than certain value by using javascript

I am trying to do some calculation in page, however, it doesn't work, I have tried the following code, does anyone can tell me the correct answer?
For example, when I enter a number then it will do one of the calculation.
<table><tr><td>
<input name="per_pax" size="2" style="border-style:none" type="text" id="per_pax" value="">
</td><td>
<input name="sum_tlcost" type="hidden" id="sum_tlcost" value="<?php echo $tl_cost;?>">
<input name="sum_htl_pp" type="hidden" id="sum_htl_pp" value="<?php echo $sum_htl_pp;?>">
<input name="sum_coach" type="hidden" id="sum_coach" value="<?php echo $sum_coach;?>">
<input name="pax" size="5" readonly="readonly" type="text" id="pax" value="">
</td></tr></table>
<script>
$(document).ready(function () {
var total = Number($("#per_pax").val());
if(total >= 20) {
$("#sum_tlcost,#sum_htl_pp,#sum_coach,#per_pax").keyup(function () {
if (parseInt($("#per_pax").val()) >= 20) {
$("#pax").val(Math.round(Number($("#sum_htl_pp").val()) + Number($("#sum_tlcost").val()) / Number($("#per_pax").val()) + Number($("#sum_coach").val()) / Number($("#per_pax").val()));
)}else{
$("#pax").val(Math.round(Number($("#sum_htl_pp").val()) + Number($("#sum_tlcost").val()) + Number($("#sum_coach").val())))
}
})}})
</script>
I'm not overly fond of the jquery keyup calls... so here's a snippet that should call your function using normal DOM event calls. The input event triggers as they type.. which should be similar to what you're trying to do with the keyups... I also cleaned up the function itself to make it more readable for presentation.
function onInputChange() {
var perPax = parseInt($("#per_pax").val());
var tlCost = Number($("#sum_tlcost").val());
var htlPP = Number($("#sum_htl_pp").val());
var coach = Number($("#sum_coach").val());
var newValue = 0;
if (perPax < 20) {
newValue = (htlPP + tlCost) / (perPax + (coach / perPax));
} else {
newValue = htlPP + tlCost + coach;
}
$("#pax").val(Math.round(newValue))
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td>
<input name="per_pax" size="2" style="border-style:none" type="text" id="per_pax" value="" oninput="onInputChange()">
</td>
<td>
<input name="sum_tlcost" type="hidden" id="sum_tlcost" value="<?php echo $tl_cost;?>">
<input name="sum_htl_pp" type="hidden" id="sum_htl_pp" value="<?php echo $sum_htl_pp;?>">
<input name="sum_coach" type="hidden" id="sum_coach" value="<?php echo $sum_coach;?>">
<input name="pax" size="5" readonly="readonly" type="text" id="pax" value="">
</td>
</tr>
</table>

jQuery/Javascript complex iterate over elements

We have a form and need to iterate over some elements to get the final sum to put in a "total" element.
E.g., here is a working starter script. It doesn't NOT iterate over the other ones. It does NOT consider the elements "item*", below, yet but should. Keep reading.
<script>
$( document ).ready(function() {
$('#taxsptotal').keyup(calcgrand);
$('#shiptotal').keyup(calcgrand);
$('#disctotal').keyup(calcgrand);
function calcgrand() {
var grandtot = parseFloat($('#subtotal').val(), 10)
+ parseFloat($("#taxsptotal").val(), 10)
+ parseFloat($("#shiptotal").val(), 10)
- parseFloat($("#disctotal").val(), 10)
$('#ordertotal').val(grandtot);
}
});
</script>
We are adding more to this. Think of having many items in a cart and each one has the same elements for the following where "i" is a number designating an individual item.
<!-- ordertotal = sum of #subtotal, #taxptotal, #shiptotal and #disctotal -->
<input type="text" id="ordertotal" name="ordertotal" value="106.49">
<input type="text" id="taxsptotal" name="taxsptotal" value="6.72">
<input type="text" id="shiptotal" name="shiptotal" value="15.83">
<input type="text" id="disctotal" name="disctotal" value="0.00">
<!-- sum of the cart "itemtotal[i]" -->
<input type="text" id="subtotal" name="subtotal" value="83.94">
<!-- cart items
User can change any itemprice[i] and/or itemquantity[i]
itemtotal[i] = sum(itemquantity[i] * itemprice[i])
-->
<input type="text" name="itemtotal[1]" value="8.97" />
<input type="text" name="itemquantity[1]" value="3" />
<input type="text" name="itemprice[1]" value="2.99" />
<input type="text" name="itemtotal[2]" value="4.59" />
<input type="text" name="itemquantity[2]" value="1" />
<input type="text" name="itemprice[2]" value="4.59" />
<input type="text" name="itemtotal[3]" value="0.99" />
<input type="text" name="itemquantity[3]" value="10" />
<input type="text" name="itemprice[3]" value="9.90" />
(1) User can change any itemprice[i] and/or itemquantity[i], so each needs a keyup. I can do that in php as it iterates over the items.
(2) These elements will have a $('.itemtotal[i]').keyup(calcgrand); (Or function other than calcgrand, if needed) statement, too. That keyup can be added by the php code as it evaluates the items in the cart.
(3) When an element is changed, then the script should automatically (a) calculate the $('[name="itemtotal[i]"]').val() and (b) replace the value for $('[name="itemtotal[i]"]').val().
(4) Then, the script above will use the $('[name="itemtotal[i]"]').val() to (a) replace the #subtotal value and (b) use that value in the equation.
Can someone help me with this? I am stuck on how to iterate over the [i] elements.
p.s. Any corrections/enhancements to the above code is appreciated, too.
Add a custom class to the desired inputs to sum:
HTML:
<input type="text" class="customclass" name=itemtotal[1] value="8.97" />
<input type="text" class="customclass" name=itemquantity[1] value="3" />
<input type="text" class="customclass" name=itemprice[1] value="2.99" />
JS:
var sum = 0;
$.each('.customclass',function(i, item){
sum = sum + Number($(this).val());
})
alert(sum);
if you for example group your inputs by giving them a class, or have each group in a div like so:
<!-- ordertotal = sum of #subtotal, #taxptotal, #shiptotal and #disctotal -->
<input type="text" id="ordertotal" name="ordertotal" value="106.49">
<input type="text" id="taxsptotal" name="taxsptotal" value="6.72">
<input type="text" id="shiptotal" name="shiptotal" value="15.83">
<input type="text" id="disctotal" name="disctotal" value="0.00">
<!-- sum of the cart "itemtotal[i]" -->
<input type="text" id="subtotal" name="subtotal" value="83.94">
<!-- cart items
User can change any itemprice[i] and/or itemquantity[i]
itemtotal[i] = sum(itemquantity[i] * itemprice[i])
-->
<div class="group">
<input type="text" name="itemtotal[1]" value="8.97" />
<input type="text" name="itemquantity[1]" value="3" />
<input type="text" name="itemprice[1]" value="2.99" />
</div>
<div class="group">
<input type="text" name="itemtotal[2]" value="4.59" />
<input type="text" name="itemquantity[2]" value="1" />
<input type="text" name="itemprice[2]" value="4.59" />
</div>
<div class="group">
<input type="text" name="itemtotal[3]" value="0.99" />
<input type="text" name="itemquantity[3]" value="10" />
<input type="text" name="itemprice[3]" value="9.90" />
</div>
Then you could do the following in javascript:
function calcSubTotal() {
$('[name^="itemtotal"]').each(function(i){
var sum = 0;
$('[name^="itemtotal"]').each(function(i){
sum += $(this).val();
});
$('#subtotal').val(sum);
});
}
$('.group').each(function(i) {
var total = $(this).find('[name^="itemtotal"]');
var qnt = $(this).find('[name^="itemquantity"]');
var price = $(this).find('[name^="itemprice"]');
total.keyup(function(e){
price.val(total.val() * qnt.val());
calcSubTotal();
});
qnt.keyup(function(e){
price.val(total.val() * qnt.val());
calcSubTotal();
});
});
$("[name^='itemprice'], [name^='itemquantity']").keyup(function(){
var input_name = $(this).attr('name');
var temp_name_split = input_name.split(/[\[\]]+/);
var temp_total = parseInt($('[name="itemquantity['+temp_name_split[1] +']"]').val()) * parseFloat($('[name="itemprice['+temp_name_split[1] +']"]').val());
$('[name="itemtotal['+temp_name_split[1]+']"]').val(temp_total.toFixed(2));
var total = 0;
$("[name^='itemtotal']").each(function() {
total += parseFloat($(this).val());
});
$('#subtotal').val(total.toFixed(2));
});

Javascript: Update price when quantity changes

I am new to javascript and I have been working on this for 4 days now and I haven't made any progress. I have tried a bunch of different options. I saw an example like mine that worked...but it isn't working for me. :( I am trying to have the price adjust as the quantity of tickets changes. Below is the javascript and below that is the html. Any assistance is much appreciated! Thank you!
document.getElementById("totalTicketCost").value = 0 + "." + 00;
function ticketCost()
{
var ticketCost = 5.5;
var inputTicketQuantity = document.getElementById("inputTicketQuantity").value;
var totalTicketCost = parseFloat(ticketCost) * inputTicketQuantity;
if (!isNaN(totalTicketCost))
document.getElementById("totalTicketCost").innerHTML = totalTicketCost;
}
<form onsubmit="" ="return alertDetails()" id="formPurchaseTickets" enctype="text/plain" method="post" action="mailto:cmst388#xyz.com">
<h1>Ticket Purchasing Form</h1>
<p class="alert">Act fast! This transaction must be completed in <span id="timer"></span> minutes.</p>
<div class="field">
<label class="required">How many tickets would you like to purchase?</label>
<input id="inputTicketQuantity" tabindex="1" required type="number" value="0" name="ticket-quantity" min="1" max="3" step="1" title="You can only buy between 1 and 3 tickets">
$<span id="totalTicketCost">0.00</span>
</div>
<div id="contactInfo" style="display:none;">
<div class="field">
<label class="required">Name:</label>
<input required name="name" tabindex="2" type="text" placeholder="Enter name" pattern="[a-zA-Z\s]+" title="Enter only letters. e.g. Smith">
</div>
<div class="field">
<label class="required">E-mail:</label>
<input id="inputEmail" tabindex="3" required name="email" type="email" placeholder="Enter e-mail address" onblur="validateEmail()">
</div>
</div>
<hr>
<input type="submit" tabindex="4" value="Purchase Tickets"> <input type="reset">
</form>
<script src="event_registration.js"></script>
</body>
Going with only ES5 here (assuming you're not transpiling at this stage), I did a quick refactor.
var ticketInput = document.getElementById("totalTicketCost");
var inputTicketQuantity = document.getElementById("inputTicketQuantity");
var ticketCost = 5.5;
// Handle the precision up to >= $100
function changeCost( num ) {
var cost = new Number( parseFloat( num ) * ticketCost );
var precision = cost.toString().length === 3 ? 3 : 4;
return cost.toPrecision( precision );
}
inputTicketQuantity.addEventListener('input', function( event ) {
var value = event.target.value;
if ( !isNaN( value ) ) {
ticketInput.innerHTML = changeCost( value );
}
});
You definitely want to separate out the JS from the HTML as much as possible, avoid the hard to read inline stuff like <form onsubmit="" ="return alertDetails()", should at least be <form onsubmit="return alertDetails()" to fix it.
Add an event listener to you quantity field, and recalculate price.
document.querySelector("#inputTicketQuantity").addEventListener("input", function() {
let count = this.value;
calculatePrice(count);
});
Your question is not very specific on what you're trying to achieve, but here is functionality to update your total cost as the user adds tickets -
In JS:
function updateCost(count)
{
var ticketCost = 5.5;
document.getElementById("totalTicketCost").innerHTML = count * ticketCost;
}
In HTML
<input id="inputTicketQuantity" tabindex="1" required type="number" value="0" name="ticket-quantity" onchange="updateCost(this.value)" min="1" max="3" step="1" title="You can only buy between 1 and 3 tickets">
You have to call function ticketCost() on value change event of input quantity textbox
<input id="inputTicketQuantity" onkeydown="ticketCost()" tabindex="1" required type="number" value="0" name="ticket-quantity" min="1" max="3" step="1" title="You can only buy between 1 and 3 tickets">
Or you can add listener in JavaScript as
document.getElementById("inputTicketQuantity").addEventListener("onkeydown", ticketCost);
Add it outside your JavaScript function ticketCost()

Adding multiple array values

Here is my form
<form method="post" action="collect_vals.php">
<div id="input_fields">
<div><input type="text" placeholder="unit" name="unit[]"> <input type="text" placeholder="price" name="price[]"><input type="text" placeholder="total" name="total[]"> <span class="fa fa-plus-circle" id="add_field"></span></div>
</div>
<input type="submit" value="submit">
</form>
https://jsfiddle.net/d9bhsL4o/1/
Here is my script:
<script type="text/javascript">
$(document).ready(function() {
$("input[name=unit]").keyup(function() {
var unit = new Array();
var qty = new Array();
$("input[name=unit]").each(function() {
unit.push($(this).val());
});
$("input[name=qty]").each(function() {
qty.push($(this).val());
});
var total = new Array();
for (var i = 0; i <unit.length; i++) {
var inp=unit[i]*qty[i];
("total["+i+"].value="+inp.value);
}
});
});
</script>
Trying to multiply two values and keep on third. Does not working. What the wrong with the code
Am attached class definition inside html both rendered and appended element. I tweak around your html code and use this to total up all values respectively :
HTML
<input type="text" placeholder="unit" name="unit[]" class="a">
<input type="text" placeholder="price" name="price[]" class="a">
<input type="text" placeholder="total" name="total[]" class="total">
JS
......
......
$("#input_fields").append('<input type="text" placeholder="unit" name="unit[]" class="a">
<input type="text" placeholder="price" name="price[]" class="a">
<input type="text" placeholder="total" name="total[]" class="total">
<span id="remove" class="fa fa-minus-circle"></span</div>');
......
......
// capture both unit AND price keyup
$("#input_fields").on('keyup', '.a', function () {
// add current keyup textbox also into stack
var all = $(this).siblings('input.a').addBack();
var sum = 1;
// loop over those element
all.each(function(i,e){
// sum both values
sum *= $(e).val();
});
// finally filtered textbox with total class
// and assign the output
$(this).nextAll('.total').val(sum);
});
DEMO
You should traverse the DOM, there are multiple ways to travese DOM. Here I have used .siblings() to get total and qty
$("#input_fields").on('keyup', "input[name='unit[]']", function () {
var unit = $(this).val();
var price = $(this).siblings("input[name='price[]']").val();
$(this).siblings("input[name='total[]']").val(unit * price);
});

Categories