Subtracting values from multiple input fields - javascript

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

Related

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>

How to check value in input using loop for with onchange using javascript?

How to check value in input using loop for with onchange using javascript ?
first, When user fill char. It's will be show Your Price must be a number.
And if user fill number less than 1.5 It's will show Your Price must be at least $1.50 USD.
and click Add more link to add input.
I try my code , but not work, how can i do that ?
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<form onsubmit="return checkform(this);">
Add more
<div id="p_scents_price">
<p>
<label>
<input type="text" class="price" id="price0" size="20" name="price[]" onchange="myFunction0()"/><p id="demo0"></p>
</label>
</p>
</div>
<input type="submit" name="submit" value="OK">
</form>
<script>
var list = document.querySelectorAll(".price");
for (z = 0; z < list.length; ++z) {
function myFunction'+z+'() {
var x = document.getElementById("price'+z+'").value;
var y = isNaN(x);
if(y === true)
{
document.getElementById("demo'+z+'").innerHTML = "Your Price must be a number.";
}
else
{
if(x < 1.5)
{
document.getElementById("demo'+z+'").innerHTML = "Your Price must be at least $1.50 USD.";
}
else
{
document.getElementById("demo'+z+'").innerHTML = "";
}
}
}
}
}
</script>
<script>
$(function() {
var scntDiv = $('#p_scents_price');
var i = 1;
$('#addScnt_price').live('click', function() {
$('<p><label><input type="text" class="price" id="price'+i+'" size="20" name="price[]" onchange="myFunction'+i+'()"/>Remove<p id="demo'+i+'"></p></label></p>').appendTo(scntDiv);
i++;
return false;
});
$('#remScnt_price').live('click', function() {
if( i > 2 ) {
$(this).parents('p').remove();
}
return false;
});
});
</script>

Js validate multipe input fields with same name

Ok i have multy fields with same name, and i want to check is all fields are not empty. My code works if i have only one input, but i have no idea how to do that with more inputs
<input class = "new_input" type=text name="name[]"/>
<input class = "new_input" type=text name="name[]"/>
function validation(){
var x = document.forms["form"]["name"].value;
if(x ==='')
{
$("#warning").html("Morate uneti vrednost!").css('color','red');
return false;
}
else
{
return true;
}
}
for example if enter only one field, validation will work, and i want to check all fields
Using just JS you could do something like
<input class="new_input" type="text" name="name[]">
<input class="new_input" type="text" name="name[]">
<input class="new_input" type="text" name="name[]">
<input class="new_input" type="text" name="name[]">
<button onclick="validate()">Validate</button>
<script type="text/javascript">
function validate() {
var inputs = document.getElementsByTagName("input");
var empty_inputs = 0;
for(var i = 0; i < inputs.length; i++) {
if(inputs[i].name.indexOf('name') == 0) { // check all inputs with 'name' in their name
if (inputs[i].value == '') {
empty_inputs++;
console.log('Input ' + i + ' is empty!');
}
}
}
if (empty_inputs == 0) {
console.log('All inputs have a value');
}
}
</script>
You have tagged jquery, so I have given something which works in jquery
http://jsfiddle.net/8uwo6fjz/1/
$("#validate").click(function(){
var x = $("input[name='name[]']")
$(x).each(function(key,val){
if($(val).val().length<=0)
{
$("#warning").html("Morate uneti vrednost!").css('color','red');
}
});
});
Try this:
function validate(){
var error = 0;
$.each( $("input[name='name[]']"), function(index,value){
if( value.value.length == 0){
$("#warning").html("Morate uneti vrednost!").css('color','red');
error = 1;
return;
}
});
if(!error){
$("#warning").html("");
}
}
Check it out here: jsFiddle

Limit Sum Value of Multiple Input Fields

I need some help with javascript or jQuery.
I have three (3) input fields that I want to filter (sum of three fields).
the total value of 3 input fields is must 100. If the user fills more than 100, it will be automatically change the value that the total is 100.
you can see this example
<input type="text" name="text1" size="3"> text1<br />
<input type="text" name="text2" size="3"> text2<br />
<input type="text" name="text3" size="3"> text3<br />
<p>The maximum value of total 3 fields above is 100.</p>
<pre>example 1 :
text1 : 20;
text2 : 30;
text3 : 50; (will automatically filled with 50 because the total value must 100)</pre>
<pre>example 2 :
text1 : 37;
text2 : 60;
text3 : 3; (will automatically filled with 3 because the total value must 100)</pre>
Thanks for helping me,
I need it :)
$("input:lt(2)").on("change", function() {
var other = $("input:lt(2)").not(this).val();
if (other.length)
$("input:eq(2)").val(100 - this.value - other);
});
DEMO: http://jsfiddle.net/D5F3p/3/
This is the simplest thing I can think of!
$(document).ready(function(){
$('input[name="text2"]').blur(function(){
$('input[name="text3"]').val(100 - $('input[name="text1"]').val() - $('input[name="text2"]').val());
});
});
IMO, you can do these:
Give only two characters for both the inputs. Don't allow more than that!
You also need to check if the sum of the two inputs should not exceed 101!
Keep the input 2 readonly, until something has been entered in input 1.
Keep the input 3 always readonly.
Fiddle: http://jsfiddle.net/praveenscience/D5F3p/5/
<head>
<script type="text/javascript">
function check() {
var sum = 0;
var inputs = $(".test");
for (i = 0; i < inputs.length; i++) {
if (inputs[i].value == parseInt(inputs[i].value)) {
sum += parseInt(inputs[i].value);
if (sum > 100) {
sum -= parseInt(inputs[i].value);
inputs[i].value = 100-sum;
}
}
}
}
</script>
</head>
<body>
<input type="text" onkeyup="check()" class="test" size="3">
<input type="text" onkeyup="check()" class="test" size="3">
<input type="text" onkeyup="check()" class="test" size="3">
$(function(){
$('input[name="text1"]').keyup(function(){
var text1Value = $('input[name="text1"]').val();
if(text1Value >=100)
{
$('input[name="text1"]').val(100);
$('input[name="text2"]').val('');
$('input[name="text3"]').val('');
$('input[name="text2"]').attr('disabled','disabled');
$('input[name="text3"]').attr('disabled','disabled');
}
else
{
$('input[name="text2"]').removeAttr('disabled');
$('input[name="text3"]').removeAttr('disabled');
}
});
$('input[name="text2"]').keyup(function(){
var text1Value = parseInt($('input[name="text1"]').val());
var text2Value = parseInt($('input[name="text2"]').val());
if(isNaN(text1Value))
{
text1Value =0;
}
if(isNaN(text2Value))
{
text2Value =0;
}
var total = text1Value + text2Value;
if(total >=100)
{
$('input[name="text2"]').val(100-text1Value);
$('input[name="text3"]').val('');
$('input[name="text3"]').attr('disabled','disabled');
}
else
{
$('input[name="text3"]').removeAttr('disabled');
$('input[name="text3"]').val(100-total);
}
});
});
I am checking if sum of all text boxes if exceeding 100, then making correction in the last entered textbox with disabling the next textbox.

Get Sum from each row form-field

I trying to calculate some rows (input fields) but it seams to hard for me :(.
The html code i have looks like this:
<table>
<tr>
<td>
<input name="Field_Price_1" id="Field_Price_1" value="20.55" type="text">
<input name="Field_Amount_1" id="Field_Amount_1" type="text">
<input name="Field_SubTotal_1" id="Field_SubTotal_1" type="text">
</td>
</tr>
<tr>
<td>
<input name="Field_Price_2" id="Field_Price_2" value="17.55" type="text">
<input name="Field_Amount_2" id="Field_Amount_2" type="text">
<input name="Field_SubTotal_2" id="Field_SubTotal_2" type="text">
</td>
</tr>
<tr>
<td>
<input name="Field_Price_3" id="Field_Price_3" value="94.20" type="text">
<input name="Field_Amount_3" id="Field_Amount_3" type="text">
<input name="Field_SubTotal_3" id="Field_SubTotal_3" type="text">
</td>
</tr>
<tr>
<td>
<input name="Field_Price_4" id="Field_Price_4" value="12.10" type="text">
<input name="Field_Amount_4" id="Field_Amount_4" type="text">
<input name="Field_SubTotal_4" id="Field_SubTotal_4" type="text">
</td>
</tr>
<tr>
<td>
<input name="Field_Price_5" id="Field_Price_5" value="7.45" type="text">
<input name="Field_Amount_5" id="Field_Amount_5" type="text">
<input name="Field_SubTotal_5" id="Field_SubTotal_5" type="text">
</td>
</tr>
So i would put the sum from all input fields "Field_Price_" in the following span by triggering "keyup" from each Field_Amount_".
<table>
<tr>
<td><span id="PrintSum">0.00</span></td>
</tr>
The following i tried:
var total = 0;
var Price = $('input[id^=Field_Price_]').val();
$.each($(Price), function(){
total += $(this).val();
});
$('#PrintSum').text(total);
So that won't work.
Do any know what is the problem? Thank you very much!
try something like this,Fiddle
var total = 0;
var Price = $('input[id^=Field_Price_]');
$.each($(Price), function(){
total += parseInt($(this).val());
});
$('#PrintSum').text(total);
use this javascript
$(':input[id^="Field_Price_"]').keyup(function() {
var total = 0;
var $inputs = $(':input[id^="Field_Price_"]');
$inputs.each(function (index)
{
total += parseFloat($(this).val());
});
alert(total);
$('#PrintSum').text(total);
});
jsFiddle
What about this solution:
var $prices = $('input[id^=Field_Price_]'),
$amounts = $('input[id^=Field_Amount_]');
$prices.add($amounts).on('keyup', function() {
var total = 0;
$prices.each(function() {
total += $(this).val() * $(this).next().val() || 0;
});
$('#PrintSum').text(total.toFixed(2));
})
.trigger('keyup');
http://jsfiddle.net/UFSvF/
Here changing the price as well as an amount triggers total price recalculation.
I guess you should be parse the input value to an float.
var total = 0;
var Price = $('input[id^=Field_Price_]').val();
$.each($(Price), function(){
total += parseFloat($(this).val());
});
$('#PrintSum').text(total);
On jsfiddle, an example not using jquery, but you could modify to do testing there
var prices = document.querySelectorAll("[id^=Field_Price]"),
ammounts = document.querySelectorAll("[id^=Field_Amount]"),
subTotals = document.querySelectorAll("[id^=Field_SubTotal]"),
printSum = document.getElementById("PrintSum");
function sumIt() {
var total = 0;
Array.prototype.forEach.call(prices, function (price, index) {
var subTotal = (parseFloat(price.value) || 0) * (parseFloat(ammounts[index].value) || 0);
subTotals[index].value = subTotal.toFixed(2);
total += subTotal;
});
printSum.textContent = total.toFixed(2);
}
Array.prototype.forEach.call(prices, function (input) {
input.addEventListener("keyup", sumIt, false);
});
Array.prototype.forEach.call(ammounts, function (input) {
input.addEventListener("keyup", sumIt, false);
});
sumIt();
Here is a jquery version of above, on jsfiddle
var prices = $("input[id^=Field_Price_]"),
amounts = $("input[id^=Field_Amount_]"),
subTotals = $("input[id^=Field_SubTotal_]"),
printSum = $("#PrintSum");
function sumIt() {
var total = 0;
prices.each(function(index, price) {
var subTotal = (parseFloat(price.value) || 0) * (parseFloat(amounts.eq(index).val()) || 0);
subTotals.eq(index).val(subTotal.toFixed(2));
total += subTotal;
});
printSum.text(total.toFixed(2));
}
prices.on("keyup", sumIt);
amounts.on("keyup", sumIt);
sumIt();
I will modify my pure javascript version soon to show you how your further questioning can be achieved, without the need of including jquery.
It has now been updated so you can see how it works
And a jsperf showing the construction performance of the two

Categories