How to make auto calculate in dynamic multiple form? - javascript

function sum()
{
$(document).on('keyup', "*[data-field='unit'],*[data-field='unit_price']", function(e)
{
var unit = document.getElementById('unit').value;
var unitPrice = document.getElementById('unit_price').value;
var result = parseInt(unit) * parseInt(unitPrice);
if (!isNaN(result))
{
document.getElementById('amount').value = result;
}
});
}
p/s: this only function at normal form. but not dynamic form.
[edit ?]
$('#unit, #price').on('input',function()
{
let qty = parseInt($('#unit').val())
, price = parseFloat($('#price').val())
;
$('#amount').val((qty * price ? qty * price : 0).toFixed(2));
});

you can do this whit jQuery Plugin i write simple one
you can test it on this :
$.fn.sum = function(options) {
"use strict";
var self = this;
self.defaults = {
unit : '[data-field="unit"]',
unit_price : '[data-field="unit_price"]',
result : '[data-field="amount"]',
onCalculate : function(result){},
};
self.settings = $.extend({},self.defaults, options );
var unit_count = $(self).find('input'+self.settings.unit).length;
var unit_price_count = $(self).find('input'+self.settings.unit_price).length;
if(unit_count > 0 && unit_price_count > 0){
var unit, unit_price=0, result=0;
$($(self).find('input'+self.settings.unit_price)).bind('keyup', function(){
unit = $(this).closest('form').find('input'+self.settings.unit).val();
unit_price = $(this).closest('form').find('input'+self.settings.unit_price).val();
result = sum(unit, unit_price);
self.settings.onCalculate(self, $(this), result);
});
$($(self).find('input'+self.settings.unit)).bind('keyup', function(){
unit = $(this).closest('form').find('input'+self.settings.unit).val();
unit_price = $(this).closest('form').find('input'+self.settings.unit_price).val();
result = sum(unit, unit_price);
self.settings.onCalculate(self, $(this), result);
});
function sum(unit, unit_price){
var result = parseInt(unit) * parseInt(unit_price);
if (!isNaN(result)) {
return result;
}
}
}
}
$(document).ready(function(){
$('form').sum({
onCalculate: function(self, active, result){
$(active).closest('form').find(self.settings.result).val(result);
},
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="fff33">
<legend>
two
</legend>
<lable>unit</lable>
<input type="text" data-field='unit' id="unit22">
<br>
<lable>unit_price</lable>
<input type="text" data-field='unit_price' id="unit_price22">
<input type="text" data-field="amount" disabled>
</form>
<br>
<br><br>
<form id="fff">
<legend>
one
</legend>
<lable>unit</lable>
<input type="text" data-field='unit' id="unit">
<br>
<lable>unit_price</lable>
<input type="text" data-field='unit_price' id="unit_price">
<input type="text" data-field="amount" disabled>
</form>
<br><br>

Related

Calculate total sum of all the numbers previously entered in a field

i want to calculate the total of the numbers entered by the user. After a user has added item name and the amount, i want to display the total. How can i do this? i just need to display the total.
For example
item name : 10
item name : 5
total = 15
http://jsfiddle.net/81t6auhd/
<body>
<header>
<h1>Exercise 5-2</h1>
</header>
<p>Item: <input type="text" id="item" size="30">
<p>Amount: <input type="text" id="amount" size="30">
<p><span id="message">*</span>
<p><input type="button" id="addbutton" value="Add Item" onClick="processInfo();">
<script>
var $ = function(id) {
return document.getElementById(id);
};
var myTransaction = [];
function processInfo ()
{
var myItem = $('item').value;
var myAmount = parseFloat($('amount').value);
var myTotal = myItem + ":" + myAmount;
var myParagraph = $('message');
myParagraph.innerHTML = "";
myTransaction.push(myTotal);
myParagraph.innerHTML += myTransaction.join("<br>");
};
(function () {
$("addbutton").onclick = processInfo;
})();
</script>
</body>
you have to stored the previous value somewhere in memory to be able to reuse it at next iteration
one proposal can be to stored it in dataset of the field
if ($('amount').dataset.previous) {
myAmount += parseFloat($('amount').dataset.previous);
}
$('amount').dataset.previous = myAmount
var $ = function(id) {
return document.getElementById(id);
};
var myTransaction = [];
function processInfo ()
{
var myItem = $('item').value;
var myAmount = parseFloat($('amount').value);
if ($('amount').dataset.previous) {
myAmount += parseFloat($('amount').dataset.previous);
}
$('amount').dataset.previous = myAmount;
var myTotal = myItem + ":" + myAmount;
var myParagraph = $('message');
myParagraph.innerHTML = "";
myTransaction.push(myTotal);
myParagraph.innerHTML += myTransaction.join("<br>");
};
(function () {
$("addbutton").onclick = processInfo;
})();
<p>Item: <input type="text" id="item" size="30">
<p>Amount: <input type="text" id="amount" size="30">
<p><span id="message">*</span>
<p><input type="button" id="addbutton" value="Add Item" onClick="processInfo();">

Auto substract both values from 100

I created two input fields where they should substract from each other keeping a max value at 100.
Currently it substracted value is shown in the second value. I want it to be interchangeable. Irrespective of whether I put in first or second input field, the answer shows in the other.
Could someone help?
function updateDue() {
var total = parseInt(document.getElementById("totalval").value);
var val2 = parseInt(document.getElementById("inideposit").value);
// to make sure that they are numbers
if (!total) { total = 0; }
if (!val2) { val2 = 0; }
var ansD = document.getElementById("remainingval");
ansD.value = total - val2;
var val1 = parseInt(document.getElementById("inideposit").value);
// to make sure that they are numbers
if (!total) { total = 0; }
if (!val1) { val1 = 0; }
var ansD = document.getElementById("remainingval");
ansD.value = total - val1;
}
<input type="hidden" id="totalval" name="totalval" value="100" onchange="updateDue()">
<div>
Enter Value:
<input type="text" name="inideposit" class="form-control" id="inideposit" onchange="updateDue()">
</div>
<div>
Substracted:
<input type="text" name="remainingval" class="form-control" id="remainingval" onchange="updateDue()">
</div>
The simple way to achieve this would be to group the inputs by class and attach a single event handler to them. Then you can take the entered value from 100, and set the result to the field which was not interacted with by the user. To do that in jQuery is trivial:
$('.updatedue').on('input', function() {
var total = parseInt($('#totalval').val(), 10) || 0;
var subtracted = total - (parseInt(this.value, 10) || 0);
$('.updatedue').not(this).val(subtracted);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="hidden" id="totalval" name="totalval" value="100" />
<div>
Enter Value:
<input type="text" name="inideposit" class="updatedue form-control" id="inideposit" />
</div>
<div>
Subtracted:
<input type="text" name="remainingval" class="updatedue form-control" id="remainingval" />
</div>
You can easily validate this so that outputs < 0 and > 100 can be discounted, if required.
Edit your code as below
function updateDue(box) {
var total = parseInt(document.getElementById("totalval").value);
if(box == 1){
var val = parseInt(document.getElementById("inideposit").value);
// to make sure that they are numbers
if (!total) { total = 0; }
if (!val) { val = 0; }
var ansD = document.getElementById("remainingval");
ansD.value = total - val;
}else if(box == 2){
var val = parseInt(document.getElementById("remainingval").value);
// to make sure that they are numbers
if (!total) { total = 0; }
if (!val) { val = 0; }
var ansD = document.getElementById("inideposit");
ansD.value = total - val;
}
}
<input type="hidden" id="totalval" name="totalval" value="100" onchange="updateDue(0)">
<div>
Enter Value:
<input type="text" name="inideposit" class="form-control" id="inideposit" onchange="updateDue(1)">
</div>
<div>
Substracted:
<input type="text" name="remainingval" class="form-control" id="remainingval" onchange="updateDue(2)">
</div>

Javascript Multiplication issue in Calculator

Multiplying 'Area' value with one of three separate fixed values (types of paint:Premium/Luxury/Regular) so as to calculate the total.
There are three values to choose from the dropdown option, but the calculator function always loads the last value as the multiplier.
Calculator works with one fixed value only
window.onload = function(){
function findID(id) { //function to make 'getElementById easier to maintain;
return document.getElementById(id);
}
var calculator = {
multOne: findID('mult-one'),
multTwo: findID('mult-two'),
multThree: findID('mult-three'),
multFour: findID('mult-four'),
product: findID('product'),
calculate: findID('calculate'),
clear: findID('clear')
};
// Onclick Events for buttons
calculator.clear.onclick = function() {
calculator.multOne.value = '';
calculator.multTwo.value = '';
calculator.multThree.value = '';
calculator.multFour.value = '';
calculator.product.value = 'Please Refresh your browser';
console.log(result = 0);
}
calculator.calculate.onclick = function() {
var result = calculator.multOne.value * calculator.multTwo.value;
console.log(result);
if(isNaN(result)) {
calculator.product.value = 'Not Valid - Try Again!!'
}
else {
calculator.product.value = result;
}
}
calculator.calculate.onclick = function() {
var result = calculator.multOne.value * calculator.multThree.value;
console.log(result);
if(isNaN(result)) {
calculator.product.value = 'Not Valid - Try Again!!'
}
else {
calculator.product.value = result;
}
}
calculator.calculate.onclick = function() {
var result = calculator.multOne.value * calculator.multFour.value;
console.log(result);
if(isNaN(result)) {
calculator.product.value = 'Not Valid - Try Again!!'
}
else {
calculator.product.value = result;
}
}
}
<form method="post">
<p class="home-widget-caption" style="color:#ff4102; font-size:14px;">Type of Paint</p>
<select name="types" style="width:120px">
<option id="mult-two" value="30">Luxury</option>
<option id="mult-three" value="20">Premium</option>
<option id="mult-four" value="10">Regular</option>
</select>
<br>
<p class="home-widget-caption" style="color:#ff4102; font-size:14px; margin-top:10px;">Painting Area</p>
<input type="text" id="mult-one" style="width:120px"> <span style="color:#999999">sq.ft.</span>
<br><br>
<div style="text-align:center">
<button type="button" id="calculate" style="padding:10px 30px 10px 30px; margin-bottom:15px">Calculate My painting cost</button>
<button type="button" id="clear" style="display:none">Clear</button>
</div>
<p class="home-widget-caption" style="color:#ff4102; font-size:16px">Your total expenditure</p>
<input type="text" id="product" style="width:270px">
<br><br>
</form>
You are not supposed to have multiple
calculator.calculate.onclick = function() {}
You must have only one, where you get the selected value of your <select>, and do the calculations.
Your <select> could have an id you would use later to get selected option value :
<select id="typesID" name="types" style="width:120px">
<option id="mult-two" value="30">Luxury</option>
<option id="mult-three" value="20">Premium</option>
<option id="mult-four" value="10">Regular</option>
</select>
Then in your JS side :
calculator.calculate.onclick = function() {
var e = document.getElementById("typesID");
var selectedValue = e.options[e.selectedIndex].value;
var result = calculator.multOne.value * selectedValue;
console.log(result);
if(isNaN(result)) {
calculator.product.value = 'Not Valid - Try Again!!'
}
else {
calculator.product.value = result;
}
}

JQuery - Use the value from a function

How can I use the value from a function in an if statement. I have a form where I was using return false in my script but I need changed it to preventDefault.
<form id="percentageBiz" method="post">
<input type="text" id="sum1">
<input type="text" id="sum2">
<input type="submit" onclick="return" value="Get Total">
</form>
<div id="display"></div>​
<script>
$('#percentageBiz').submit(function(e) {
var a = document.forms["percentageBiz"]["sum1"].value;
var b = document.forms["percentageBiz"]["sum2"].value;
var display=document.getElementById("display")
display.innerHTML=parseInt(a,10)+parseInt(b,10);
e.preventDefault();
});
if (display < 100) {
$("#display").addClass("notequal");
}
</script>
$('#percentageBiz').submit(function(e) {
e.preventDefault();
var $display = $("#display", this);
var a = $("#sum1", this).val();
var b = $("#sum2", this).val();
var sum = +a + +b;
$display.text( sum );
if ( sum < 100 ) {
$display.addClass("notequal");
}
});

Subtracting values from multiple input fields

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;
});
});

Categories