Limit Sum Value of Multiple Input Fields - javascript

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.

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>

Sum of input fields can't be more than account balance

I'm trying have users add dollar amounts to certain products that contain input fields for each product. The tricky part is the total of all fields can not exceed their account balance.
I can't seem to figure out how to detect if all input fields are more than the balance and then set the input field that has more than the balance to the remaining balance. Or, if there the remaining balance is already zero then the number entered into the input field would switch to zero/no actions would take place.
I've created a JSFiddle here. https://jsfiddle.net/12agemfe/1/
var qty = $('input[type=text]');
var accountbalance = parseInt($('#accountbalance').text());
var removebalance;
var newbalance;
$('input').on('focusout', function() {
//set removebalance to zero each time
removebalance = 0;
//get total from all input fields
$(qty).each(function() {
removebalance += parseFloat($(this).val());
});
//set current balance
newbalance = (parseFloat(accountbalance).toFixed(2)
- parseFloat(removebalance).toFixed(2));
//Needs to set input to zero and not update #accountbalance
//if entering more than #account balance
//Needs to correct input value if entered more than remaining balance
if (newbalance < 0) {
alert('You Can Not Cash out more than your Balance!');
return false;
}
//once input fields are totaled, update the balance on the screen
//should not allow negative balance and needs two decimal points
// parseFloat.fixedTo(2)
$('#accountbalance').text(newbalance);
});
//Cant submit if input is more than balance
$('input[type=submit]').click(function() {
if (newbalance < 0) {
alert('You Can Not Cash out more than your Balance!');
return false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="text" name="value[]" value="0.00">
<input type="text" name="value[]" value="0.00">
<input type="text" name="value[]" value="0.00">
<input type="text" name="value[]" value="0.00">
<input type="text" name="value[]" value="0.00">
</form>
<div id="accountbalance">500</div>
<button id="submit">Submit</button>
I have slightly changed script in fork from Your jsfiddle. Here it is -
https://jsfiddle.net/xqhnyf0k/2/
Most important changes are in consequences of newbalance lower than 0. We must in such situation change input value to value-(value below 0).
if (newbalance < 0) {
alert('You Can Not Cash out more than your Balance!');
//my code
$('#accountbalance').text("0.00"); //set 0 in balance UI
$(this).val(parseFloat(parseFloat($(this).val())+newbalance).toFixed(2)); //set currently changing input val to val +newbalance so if balance is minus it will left only possible amount
//end of my code
return false;
}
Other changes are connected with fixing convertion to float and float operations. Fo example from:
newbalance = (parseFloat(accountbalance).toFixed(2)
- parseFloat(removebalance).toFixed(2));
to
newbalance = (parseFloat(accountbalance) - parseFloat(removebalance));
Change is important because toFixed(http://www.w3schools.com/jsref/jsref_tofixed.asp) converts number to string so You where doing operation on strings not on numbers. Method toFixed should be used only to presentation.
I have done what I think you want out of this script.
Have a look.
var qty = $('input[type=text]');
var accountbalance = parseInt($('#accountbalance').text());
var removebalance;
var newbalance;
var inputCounter = 0; // zero-based
$('input').on('focusout', function() {
//set removebalance to zero each time
removebalance = 0;
//check number iput and die if letters or negative number
if (!$.isNumeric($(this).val()) || $(this).val() < 0) {
$(this).val(0);
return false;
}
//get total from all input fields
$(qty).each(function() {
removebalance += parseFloat($(this).val());
});
//set current balance
newbalance = (parseFloat(accountbalance).toFixed(2) - parseFloat(removebalance).toFixed(2));
$('#accountbalance').text(newbalance.toFixed(2));
//Needs to set input to zero and not update #accountbalance
//if entering more than #account balance
if (newbalance < 0) {
//alert('You Can Not Cash out more than your Balance!');
return false;
}
// Set values to fixed on focusout
thisValtoFixed = parseFloat($(this).val()).toFixed(2);
$(this).val(thisValtoFixed);
});
//Cant submit if input is more than balance
$('#submit').click(function() {
if (newbalance < 0) {
//alert('You Can Not Cash out more than your Balance!');
// Correcting last input
$(qty).each(function() {
var tempAmount = parseFloat($(this).val());
if (tempAmount > 0) {
$(this).val(tempAmount.toFixed(2));
inputCounter++;
}
});
// set corrected value
var lastInputAmount = parseFloat($(qty).eq(inputCounter - 1).val());
var correctedInputValue = lastInputAmount + newbalance;
$(qty).eq(inputCounter - 1).val(correctedInputValue.toFixed(2));
alert('You Can Not Cash out more than your Balance!\n\nWe corrected your last amount to ' + correctedInputValue.toFixed(2));
// Show a zero balance
$('#accountbalance').text(0.00);
newbalance = 0;
// Change the submit button for "Submit like this?"
$("#submit").text("Submit like this?");
return false;
}else{
// Ok to submit!!
alert("Submitted.");
}
});
input {
display: block;
margin-bottom: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="text" name="value[]" value="0.00">
<input type="text" name="value[]" value="0.00">
<input type="text" name="value[]" value="0.00">
<input type="text" name="value[]" value="0.00">
<input type="text" name="value[]" value="0.00">
</form>
<div id="accountbalance">500.00</div>
<button id="submit">Submit</button>

balancing two input number fields in jquery

I would like to balance two input number fields using jquery based on the max value set for both. for example its like a balance, if one side goes down the other goes up and vice versa. another example if the max value is 20 then if i enter 5 in input field one then 15 would be left in input field two.
Need the help Thanks. Haven't started coding it as yet stuck trying to figure it out.
First you need to attach the input eventhandler on all of the relevant input fields. This event handler will compare the current input value of a input fields to the total/max value variable and find the remainder accordingly. The event handler then finds the other input fields and assigns them with the appropriate remainder values.
Note: This allows you to add as many inputs as you want and it will
balance them all out. Just remember to add the balance class on the
input field.
var total = 20;
$('.balance').on('input', function() {
var value = parseInt(this.value);
if (isNaN(value)) {
this.value = value = 0;
} else if (value > total) {
this.value = value = total;
}/* else if (value < 0) {
this.value = value = 0;
}
* Remove this comment if value shouldn't be negative.
*/
var remainder = total - value;
var otherInputs = $('.balance');
otherInputs.splice($.inArray(this,otherInputs),1);
var remainderDiv = remainder/otherInputs.length;
$.each(otherInputs, function(input) {
otherInputs[input].value = remainderDiv;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" class="balance">
<input type="number" class="balance">
Update: The two inputs can be less than the max but never higher.
var max = 20;
$('.balance').on('input', function() {
var value = parseInt(this.value);
if (isNaN(value)) {
value = 0;
}
var otherInputs = $('.balance');
var sum = 0;
$.each(otherInputs, function(input) {
sum += parseInt(otherInputs[input].value);
});
if (sum > max)
this.value = max - (sum - value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" class="balance">
<input type="number" class="balance">
here's a fiddle to get you started (and maybe finished):
https://jsfiddle.net/ahmadabdul3/xwyrrw53/1/
html:
<input type='number' id='first' class='balancable'/>
<input type='number' id='second' class='balancable'/>
js:
$(function() {
var max = 20;
var balanceOpposite = {
'first': 'second',
'second': 'first',
}
$('.balancable').on('input', function() {
var id = $(this).attr('id');
var thisVal = $(this).val();
$('#' + balanceOpposite[id]).val(20 - thisVal);
});
});

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>

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