Auto substract both values from 100 - javascript

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>

Related

adding new value to variable

I have a question I have simple JavaScript that do some basic stuff to a number from input. I have a question how can I make variable that will always track the new input value for example if I enter 123 and click on some of the following buttons I get the result, but if I now enter new number for example 54321 and click again on some of the buttons I start from the previous value. How can I make my variable change every time a new value is entered or changed ? Here is my code:
var number = document.getElementById("number");
var numberValue = number.value;
console.log(numberValue);
function plus() {
number.value = ++numberValue;
}
function minus() {
number.value = --numberValue;
}
function flip() {
var temp = numberValue;
var cifra, prevrten = 0;
while (temp > 0) {
cifra = temp % 10;
prevrten = (prevrten * 10) + cifra;
temp = temp / 10 | 0;
}
number.value = prevrten;
}
window.onload = function() {
number.value = "";
}
<div>
<input type="text" id="number" id="output" onload="restart();">
<input type="button" value="<" onclick="minus();">
<input type="button" value=">" onclick="plus();">
<input type="button" value="FLIP" onclick="flip();">
<input type="button" value="STORE" onclick="store();">
<input type="button" value="CHECK" onclick="check();">
</div>
I suggest you use a type="number" and case the value to number - her I use the unary plus to do so
You will need to read the value in all functions
let numberValue = 0;
function store() {}
function check() {}
function plus() {
numberValue = +number.value;
number.value = ++numberValue;
}
function minus() {
numberValue = +number.value;
number.value = --numberValue;
}
function flip() {
let numberValue = +number.value;
var cifra, prevrten = 0;
while (numberValue > 0) {
cifra = numberValue % 10;
prevrten = (prevrten * 10) + cifra;
numberValue = numberValue / 10 | 0;
}
number.value = prevrten;
}
window.addEventListener("load", function() {
let number = document.getElementById("number");
number.value = 0;
})
<div>
<input type="number" id="number" id="output" onload="restart();">
<input type="button" value="<" onclick="minus();">
<input type="button" value=">" onclick="plus();">
<input type="button" value="FLIP" onclick="flip();">
<input type="button" value="STORE" onclick="store();">
<input type="button" value="CHECK" onclick="check();">
</div>
Try using onChange="".
<input type="text" id="number" id="output" onload="restart();" onChange="updateVal();">
function updateVal() {
numberValue = number.value;
}
I would suggest, for something like this, it would be much easier to use React JS or another framework with state.

trying to link checkbox list with multiple functions using HTML & JAVASCRIPT

my code calculates the AVG or MAX of an input set of numbers, I want the user to check on a checkbox list that contains AVG and MAX for desired output but I couldn't figure out doing it.
if I put an input of "2,4" without check listing the output is both AVG and MAX which is 3 4, I tried to checklist for only AVG or MAX outcome but it didn't work.
I have checked both function calculateAVG() & calculateMAX() and they produce correct output
function proccesFloat(flt) {
var splitFloat = flt.split(",");
for (x in splitFloat) {
splitFloat[x] = parseFloat(splitFloat[x]);
}
return splitFloat;
}
function calculateAVG(setNum) {
let total = 0;
var numInput = document.getElementById("setNum").value;
var result = 0;
var avg = proccesFloat(numInput);
for (let i = 0; i < avg.length; i++) {
total += avg[i];
}
result = total / avg.length;
document.getElementById('outputAVG').innerHTML = result;
}
function calculateMAX(setNum) {
var numInput = document.getElementById("setNum").value;
var numarry = proccesFloat(numInput);
var max = 0;
for (let i = 0; i < numarry.length; i++) {
if (numarry[i] > max) {
max = numarry[i];
}
}
document.getElementById('outputMAX').innerHTML = max;
}
function calculate() {
var checkBox = document.getElementsByTagName("check");
if (checkBox[0].checked) {
calculateAVG(document.getElementById("setNum"));
}
if (checkBox[0].checked) {
calculateMAX(document.getElementById("setNum"));
} {
alert('please choose formula')
return false;
}
}
<header>
<input type="Numbers" id="setNum" placeholder="Enter Set of Numbers">
<br>
<button onclick="calculate()" id="btn1">calculate</button>
<output id="outputAVG"></output>
<output id="outputMAX"></output>
<form method="post">
<fieldset>
<legend>Formula To Calculate?</legend>
<input type="checkbox" id="avg" name="check" onclick="calculate()">AVG<br>
<input type="checkbox" id="max" name="check" onclick="calculate()">MAX<br>
<br>
</fieldset>
</form>
</header>
Count the checked and then look at the IDs.
I also suggest you wrap in a form and use the submit event
I made a few more changes to simplify the code
Let the functions do one thing and use the event to bring them together
const proccesFloat = flt => flt.split(",").map(fl => +fl); // cast to float
const calculateAVG = setNum => {
const arr = proccesFloat(setNum);
const total = arr.reduce((a, b) => a + b)
return total / arr.length;
}
const calculateMAX = setNum => Math.max(...proccesFloat(setNum));
document.getElementById("calcForm").addEventListener("submit", function(e) {
e.preventDefault(); // stop submission
const chks = document.querySelectorAll("[name=check]:checked")
if (chks.length === 0) {
alert('please choose formula')
return
}
if (document.getElementById("avg").checked) {
document.getElementById('outputAVG').innerHTML = calculateAVG(document.getElementById("setNum").value);
}
if (document.getElementById("max").checked) {
document.getElementById('outputMAX').innerHTML = calculateMAX(document.getElementById("setNum").value);
}
})
<header>
<form id="calcForm">
<input type="Numbers" id="setNum" placeholder="Enter Set of Numbers">
<br>
<button type="submit">calculate</button>
<output id="outputAVG"></output>
<output id="outputMAX"></output>
<fieldset>
<legend>Formula To Calculate?</legend>
<input type="checkbox" id="avg" name="check">AVG<br>
<input type="checkbox" id="max" name="check">MAX<br>
<br>
</fieldset>
</form>
</header>

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>

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.

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