Resetting InnerHTML - javascript

I've been looking at past submissions regarding this and haven't been able to find a solution that seems to work.
I have a simple form that calculates and then increments a value. The innerHTML output ("YourAmount") works fine the first time the form is submitted. However, if I resubmit the form with another amount, the original output flickers the old calculated results with the new one. How do I reset the innerHTML output?
Thanks!
// function for formatting numbers in currency format
function CurrencyFormatted(amount) {
var i = parseFloat(amount);
if (isNaN(i)) {
i = 0.00;
}
var minus = '';
if (i < 0) {
minus = '-';
}
i = Math.abs(i);
i = parseInt((i + .005) * 100);
i = i / 100;
s = new String(i);
if (s.indexOf('.') < 0) {
s += '.00';
}
if (s.indexOf('.') == (s.length - 2)) {
s += '0';
}
s = minus + s;
s = CommaFormatted(s)
return s;
}
// function for formatting numbers with embedded commas
function CommaFormatted(amount) {
var delimiter = ","; // replace comma if desired
var a = amount.split('.', 2)
var d = a[1];
var i = parseInt(a[0]);
if (isNaN(i)) {
return '';
}
var minus = '';
if (i < 0) {
minus = '-';
}
i = Math.abs(i);
var n = new String(i);
var a = [];
while (n.length > 3) {
var nn = n.substr(n.length - 3);
a.unshift(nn);
n = n.substr(0, n.length - 3);
}
if (n.length > 0) {
a.unshift(n);
}
n = a.join(delimiter);
if (d.length < 1) {
amount = n;
} else {
amount = n + '.' + d;
}
amount = minus + amount;
return amount;
}
function calculate() {
var NumStores = document.getElementById('NumStores').value;
var result = document.getElementById('result');
var baseProfit = NumStores * 50.00;
result.value = baseProfit;
var baseProfitOverYear = baseProfit * 360; // base profit (stores x cost) over 360 days
var result2 = document.getElementById('result2');
result2.value = baseProfitOverYear;
var amount = baseProfitOverYear; // load from server
var delay = 1000; // milliseconds
var incAmount = 20; // change to the amount by which you wish to increment
var tId = setInterval(function() {
document.getElementById("YourAmount").innerHTML = "$" + CurrencyFormatted(amount += incAmount);
}, delay)
}
// disable enter key
$(document).keypress(
function(event) {
if (event.which == '13') {
event.preventDefault();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="thisForm">
<input id="NumStores" type="number" required />
<input type="button" onClick="calculate()" value="Calculate">
</form>
<br><br>
<p id="YourAmount">Your Amount Is 0</p>

First, you should create a span tag within the paragraph tag to hold the value. Then make sure you only have one interval occurring at a time.
// Document elements and variables
var numStores = document.getElementById('num-stores'),
result = document.getElementById('result-1'),
result2 = document.getElementById('result-2'),
yourAmount = document.getElementById('your-amount'),
intervalId = null; // We need to rember this...
// Constants
var profitMargin = 50.00,
numberOfDays = 360,
incAmount = 20, // change to the amount by which you wish to increment
timerDelay = 1000; // milliseconds
function calculate() {
var inputValue = numStores.value;
var baseProfit = inputValue * profitMargin;
var baseProfitOverYear = baseProfit * numberOfDays; // base profit (stores x cost) over 360 days
var amount = baseProfitOverYear; // load from server
result.value = baseProfit;
result2.value = baseProfitOverYear;
clearInterval(intervalId); // Clear the GLOBAL interval, before we start a new one.
intervalId = setInterval(function() {
yourAmount.innerHTML = "$" + CurrencyFormatted(amount += incAmount);
}, timerDelay);
}
// Disable enter key
$(document).keypress(function(event) {
if (event.which == '13') {
event.preventDefault();
}
});
// function for formatting numbers in currency format
function CurrencyFormatted(amount) {
var i = parseFloat(amount);
if (isNaN(i)) {
i = 0.00;
}
var minus = '';
if (i < 0) {
minus = '-';
}
i = Math.abs(i);
i = parseInt((i + .005) * 100);
i = i / 100;
s = new String(i);
if (s.indexOf('.') < 0) {
s += '.00';
}
if (s.indexOf('.') == (s.length - 2)) {
s += '0';
}
s = minus + s;
s = CommaFormatted(s)
return s;
}
// function for formatting numbers with embedded commas
function CommaFormatted(amount) {
var delimiter = ","; // replace comma if desired
var a = amount.split('.', 2)
var d = a[1];
var i = parseInt(a[0]);
if (isNaN(i)) {
return '';
}
var minus = '';
if (i < 0) {
minus = '-';
}
i = Math.abs(i);
var n = new String(i);
var a = [];
while (n.length > 3) {
var nn = n.substr(n.length - 3);
a.unshift(nn);
n = n.substr(0, n.length - 3);
}
if (n.length > 0) {
a.unshift(n);
}
n = a.join(delimiter);
if (d.length < 1) {
amount = n;
} else {
amount = n + '.' + d;
}
amount = minus + amount;
return amount;
}
label { font-weight: bold; }
.input-field { display: block; }
.input-field label { display: inline-block; width: 7.667em;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="this-form">
<label>Number of Stores</label> <input id="num-stores" type="number" required />
<input type="button" onClick="calculate()" value="Calculate">
</form>
<br>
<p>Your amount is: <span id="your-amount">$0.00</span></p>
<div class="input-field"><label>Base Profit</label> <input type="text" id="result-1" /></div>
<div class="input-field"><label>Annual Profit</label> <input type="text" id="result-2" /></div>

Related

Set default value to an Input field but make it editable (to be able to change it manually)?

I have an online form that takes values from some input fields and does some calculations on them. please check fiddle URL:
https://jsfiddle.net/moeadas/fv027knx/44/
I basically need to set a default value to a specific input field named (Rounded Valuation) name="B200". I want this input to take the value from another field name="B52" as default but I want users to be able to manually edit this field to enter another number (which will be used for other calculations).
Finally I want to hide the "Submit" button in the last stage as this is not really a form and its just an online form which users can play with.
I really appreciate all your kind comments and efforts. Please have a look at the fiddle link to better understand the current structure.
JAVASCRIPT CODE BELOW. CHECK THE JSFIDDLE FOR THE FULL STRUCTURE
function milesIt(num) {
return Math.floor(num).toString().split("").reverse().map((n, i, a) =>
(i + 1) % 3 === 0 && i + 1 != a.length && "," + n || n).reverse().join("");
}
var inputs = document.querySelectorAll("[type='text']");
inputs.forEach(function(input) {
//change the values to include the thousand separator each time the user changes an input
input.onchange = function(e) {
inputs.forEach(function(inp) {
inp.value = inp.value.replace(/[,]/g, '');
});
calcule2();
inputs.forEach(function(inp) {
inp.value = milesIt(inp.value);
});
}
input.value = milesIt(input.value);
});
////////////////////////////////////////////
var currentTab = 0; // Current tab is set to be the first tab (0)
showTab(currentTab); // Display the current tab
function showTab(n) {
// This function will display the specified tab of the form ...
var x = document.getElementsByClassName("tab");
x[n].style.display = "block";
// ... and fix the Previous/Next buttons:
if (n == 0) {
document.getElementById("prevBtn").style.display = "none";
} else {
document.getElementById("prevBtn").style.display = "inline";
}
if (n == (x.length - 1)) {
document.getElementById("nextBtn").innerHTML = "Submit";
} else {
document.getElementById("nextBtn").innerHTML = "Next";
}
// ... and run a function that displays the correct step indicator:
fixStepIndicator(n)
}
function nextPrev(n) {
// This function will figure out which tab to display
var x = document.getElementsByClassName("tab");
// Exit the function if any field in the current tab is invalid:
if (n == 1 && !validateForm()) return false;
// Hide the current tab:
x[currentTab].style.display = "none";
// Increase or decrease the current tab by 1:
currentTab = currentTab + n;
// if you have reached the end of the form... :
if (currentTab >= x.length) {
//...the form gets submitted:
document.getElementById("CreativeAcquisitions").submit();
return false;
}
// Otherwise, display the correct tab:
showTab(currentTab);
}
function validateForm() {
// This function deals with validation of the form fields
var x, y, i, valid = true;
x = document.getElementsByClassName("tab");
y = x[currentTab].getElementsByTagName("input");
// A loop that checks every input field in the current tab:
for (i = 0; i < y.length; i++) {
// If a field is empty...
if (y[i].value == "") {
// add an "invalid" class to the field:
y[i].className += " invalid";
// and set the current valid status to false:
valid = false;
}
}
// If the valid status is true, mark the step as finished and valid:
if (valid) {
document.getElementsByClassName("step")[currentTab].className += " finish";
}
return valid; // return the valid status
}
function fixStepIndicator(n) {
// This function removes the "active" class of all steps...
var i, x = document.getElementsByClassName("step");
for (i = 0; i < x.length; i++) {
x[i].className = x[i].className.replace(" active", "");
}
//... and adds the "active" class to the current step:
x[n].className += " active";
}
function calcule2() {
var i = 0;
for (i = 0; i <= 50; i++) {
calcule();
}
}
function calcule() {
CreativeAcquisitions.B28.value = parseFloat(CreativeAcquisitions.B17.value) + parseFloat(CreativeAcquisitions.B19.value) + parseFloat(CreativeAcquisitions.B21.value) + parseFloat(CreativeAcquisitions.B23.value) + parseFloat(CreativeAcquisitions.B25.value);
CreativeAcquisitions.B52.value = (parseFloat(CreativeAcquisitions.B4.value) * parseFloat(CreativeAcquisitions.B6.value)) + parseFloat(CreativeAcquisitions.D81.value) +
parseFloat(CreativeAcquisitions.B300.value);
CreativeAcquisitions.B55.value = parseFloat(CreativeAcquisitions.B4.value) * parseFloat(CreativeAcquisitions.B6.value);
CreativeAcquisitions.B56.value = parseFloat(CreativeAcquisitions.B28.value);
//CreativeAcquisitions.B200.value = CreativeAcquisitions.B52.value; //testing
//document.getElementById("B200").value = CreativeAcquisitions.B52.value;
CreativeAcquisitions.B66.value = parseFloat(CreativeAcquisitions.B200.value);
CreativeAcquisitions.B67.value = parseFloat(CreativeAcquisitions.D81.value);
CreativeAcquisitions.B68.value = parseFloat(CreativeAcquisitions.B36.value) + parseFloat(CreativeAcquisitions.B37.value) + parseFloat(CreativeAcquisitions.B38.value) + parseFloat(CreativeAcquisitions.B39.value) + parseFloat(CreativeAcquisitions.B40.value);
CreativeAcquisitions.B300.value = (parseFloat(CreativeAcquisitions.B36.value) + parseFloat(CreativeAcquisitions.B37.value) + parseFloat(CreativeAcquisitions.B38.value) + parseFloat(CreativeAcquisitions.B39.value) + parseFloat(CreativeAcquisitions.B40.value)) * -1;
CreativeAcquisitions.B69.value = parseFloat(CreativeAcquisitions.B41.value);
CreativeAcquisitions.B70.value = (parseFloat(CreativeAcquisitions.B200.value) * parseFloat(CreativeAcquisitions.B46.value)) / 100;
CreativeAcquisitions.B71.value = (parseFloat(CreativeAcquisitions.B200.value) * parseFloat(CreativeAcquisitions.B47.value)) / 100;
CreativeAcquisitions.B72.value = parseFloat(CreativeAcquisitions.B66.value) - parseFloat(CreativeAcquisitions.B67.value) - parseFloat(CreativeAcquisitions.B70.value) - parseFloat(CreativeAcquisitions.B69.value) - parseFloat(CreativeAcquisitions.B71.value);
CreativeAcquisitions.B76.value = parseFloat(CreativeAcquisitions.B17.value);
CreativeAcquisitions.D76.value = (parseFloat(CreativeAcquisitions.B76.value) * parseFloat(CreativeAcquisitions.C76.value)) / 100;
CreativeAcquisitions.B77.value = parseFloat(CreativeAcquisitions.B19.value);
CreativeAcquisitions.D77.value = (parseFloat(CreativeAcquisitions.B77.value) * parseFloat(CreativeAcquisitions.C77.value)) / 100;
CreativeAcquisitions.B78.value = parseFloat(CreativeAcquisitions.B21.value);
CreativeAcquisitions.D78.value = (parseFloat(CreativeAcquisitions.B78.value) * parseFloat(CreativeAcquisitions.C78.value)) / 100;
CreativeAcquisitions.B79.value = parseFloat(CreativeAcquisitions.B23.value);
CreativeAcquisitions.D79.value = (parseFloat(CreativeAcquisitions.B79.value) * parseFloat(CreativeAcquisitions.C79.value)) / 100;
CreativeAcquisitions.B80.value = parseFloat(CreativeAcquisitions.B25.value);
CreativeAcquisitions.D80.value = (parseFloat(CreativeAcquisitions.B80.value) * parseFloat(CreativeAcquisitions.C80.value)) / 100;
CreativeAcquisitions.B81.value = parseFloat(CreativeAcquisitions.B76.value) + parseFloat(CreativeAcquisitions.B77.value) + parseFloat(CreativeAcquisitions.B78.value) + parseFloat(CreativeAcquisitions.B79.value) + parseFloat(CreativeAcquisitions.B80.value);
CreativeAcquisitions.D81.value = parseFloat(CreativeAcquisitions.D76.value) + parseFloat(CreativeAcquisitions.D77.value) + parseFloat(CreativeAcquisitions.D78.value) + parseFloat(CreativeAcquisitions.D79.value) + parseFloat(CreativeAcquisitions.D80.value);
CreativeAcquisitions.B91.value = parseFloat(CreativeAcquisitions.B36.value);
CreativeAcquisitions.B92.value = parseFloat(CreativeAcquisitions.B37.value);
CreativeAcquisitions.B93.value = parseFloat(CreativeAcquisitions.B38.value);
CreativeAcquisitions.B94.value = parseFloat(CreativeAcquisitions.B39.value);
CreativeAcquisitions.B95.value = parseFloat(CreativeAcquisitions.B40.value);
CreativeAcquisitions.B96.value = (parseFloat(CreativeAcquisitions.B52.value) * parseFloat(CreativeAcquisitions.B46.value)) / 100;
CreativeAcquisitions.B97.value = parseFloat(CreativeAcquisitions.B41.value);
CreativeAcquisitions.B98.value = (parseFloat(CreativeAcquisitions.B91.value) + parseFloat(CreativeAcquisitions.B92.value) + parseFloat(CreativeAcquisitions.B93.value) + parseFloat(CreativeAcquisitions.B94.value) + parseFloat(CreativeAcquisitions.B95.value) + parseFloat(CreativeAcquisitions.B96.value) + parseFloat(CreativeAcquisitions.B97.value)) * -1;
CreativeAcquisitions.C98.value = (parseFloat(CreativeAcquisitions.C91.value) + parseFloat(CreativeAcquisitions.C92.value) + parseFloat(CreativeAcquisitions.C93.value) + parseFloat(CreativeAcquisitions.C94.value) + parseFloat(CreativeAcquisitions.C95.value) + parseFloat(CreativeAcquisitions.C96.value) + parseFloat(CreativeAcquisitions.C97.value)) * -1;
CreativeAcquisitions.B101.value = parseFloat(CreativeAcquisitions.B4.value);
CreativeAcquisitions.B105.value = (parseFloat(CreativeAcquisitions.B101.value) * parseFloat(CreativeAcquisitions.B103.value)) / 100;
CreativeAcquisitions.B107.value = parseFloat(CreativeAcquisitions.C98.value);
CreativeAcquisitions.B108.value = parseFloat(CreativeAcquisitions.B101.value) - parseFloat(CreativeAcquisitions.B105.value) + parseFloat(CreativeAcquisitions.B107.value);
}
I don't know how these fields are created but following your code, this may be helpful:
//////////Newcode///////////////////////////
function milesIt(num) {
return Math.floor(num).toString().split("").reverse().map((n, i, a) =>
(i + 1) % 3 === 0 && i + 1 != a.length && "," + n || n).reverse().join("");
}
var inputs = document.querySelectorAll("[type='text']");
inputs.forEach(function(input) {
//change the values to include the thousand separator each time the user changes an input
input.onchange = function(e) {
inputs.forEach(function(inp) {
inp.value = inp.value.replace(/[,]/g, '');
});
calcule2();
inputs.forEach(function(inp) {
inp.value = milesIt(inp.value);
});
//e.target.value = milesIt(e.target.value.replace(/[.]/g, ''));
}
//change the values of the inputs at the beginning, although you could write them as HTML with the thousand separator values in the source code
input.value = milesIt(input.value);
});
////////////////////////////////////////////
var currentTab = 0; // Current tab is set to be the first tab (0)
showTab(currentTab); // Display the current tab
function showTab(n) {
// This function will display the specified tab of the form ...
var x = document.getElementsByClassName("tab");
x[n].style.display = "block";
// ... and fix the Previous/Next buttons:
if (n == 0) {
document.getElementById("prevBtn").style.display = "none";
} else {
document.getElementById("prevBtn").style.display = "inline";
}
if (n == (x.length - 1)) {
document.getElementById("nextBtn").style.display='none';
} else {
document.getElementById("nextBtn").innerHTML = "Next";
}
// ... and run a function that displays the correct step indicator:
fixStepIndicator(n)
}
function nextPrev(n) {
// This function will figure out which tab to display
var x = document.getElementsByClassName("tab");
// Exit the function if any field in the current tab is invalid:
if (n == 1 && !validateForm()) return false;
// Hide the current tab:
x[currentTab].style.display = "none";
// Increase or decrease the current tab by 1:
currentTab = currentTab + n;
// if you have reached the end of the form... :
if (n < (x.length - 2))
document.getElementById("nextBtn").style.display='inline';
// Otherwise, display the correct tab:
showTab(currentTab);
}
function validateForm() {
// This function deals with validation of the form fields
var x, y, i, valid = true;
x = document.getElementsByClassName("tab");
y = x[currentTab].getElementsByTagName("input");
// A loop that checks every input field in the current tab:
for (i = 0; i < y.length; i++) {
// If a field is empty...
if (y[i].value == "") {
// add an "invalid" class to the field:
y[i].className += " invalid";
// and set the current valid status to false:
valid = false;
}
}
// If the valid status is true, mark the step as finished and valid:
if (valid) {
document.getElementsByClassName("step")[currentTab].className += " finish";
}
return valid; // return the valid status
}
function fixStepIndicator(n) {
// This function removes the "active" class of all steps...
var i, x = document.getElementsByClassName("step");
for (i = 0; i < x.length; i++) {
x[i].className = x[i].className.replace(" active", "");
}
//... and adds the "active" class to the current step:
x[n].className += " active";
}
function calcule2() {
var i = 0;
for (i = 0; i <= 50; i++) {
calcule();
}
}
function calcule() {
CreativeAcquisitions.B28.value = parseFloat(CreativeAcquisitions.B17.value) + parseFloat(CreativeAcquisitions.B19.value) + parseFloat(CreativeAcquisitions.B21.value) + parseFloat(CreativeAcquisitions.B23.value) + parseFloat(CreativeAcquisitions.B25.value);
CreativeAcquisitions.B52.value = (parseFloat(CreativeAcquisitions.B4.value) * parseFloat(CreativeAcquisitions.B6.value)) + parseFloat(CreativeAcquisitions.D81.value) +
parseFloat(CreativeAcquisitions.B300.value);
CreativeAcquisitions.B55.value = parseFloat(CreativeAcquisitions.B4.value) * parseFloat(CreativeAcquisitions.B6.value);
CreativeAcquisitions.B56.value = parseFloat(CreativeAcquisitions.B28.value);
CreativeAcquisitions.B200.value = Math.round(parseFloat(CreativeAcquisitions.B52.value)); //here is your field
CreativeAcquisitions.B66.value = parseFloat(CreativeAcquisitions.B200.value);
CreativeAcquisitions.B67.value = parseFloat(CreativeAcquisitions.D81.value);
CreativeAcquisitions.B68.value = parseFloat(CreativeAcquisitions.B36.value) + parseFloat(CreativeAcquisitions.B37.value) + parseFloat(CreativeAcquisitions.B38.value) + parseFloat(CreativeAcquisitions.B39.value) + parseFloat(CreativeAcquisitions.B40.value);
CreativeAcquisitions.B300.value = (parseFloat(CreativeAcquisitions.B36.value) + parseFloat(CreativeAcquisitions.B37.value) + parseFloat(CreativeAcquisitions.B38.value) + parseFloat(CreativeAcquisitions.B39.value) + parseFloat(CreativeAcquisitions.B40.value)) * -1;
CreativeAcquisitions.B69.value = parseFloat(CreativeAcquisitions.B41.value);
CreativeAcquisitions.B70.value = (parseFloat(CreativeAcquisitions.B200.value) * parseFloat(CreativeAcquisitions.B46.value)) / 100;
CreativeAcquisitions.B71.value = (parseFloat(CreativeAcquisitions.B200.value) * parseFloat(CreativeAcquisitions.B47.value)) / 100;
CreativeAcquisitions.B72.value = parseFloat(CreativeAcquisitions.B66.value) - parseFloat(CreativeAcquisitions.B67.value) - parseFloat(CreativeAcquisitions.B70.value) - parseFloat(CreativeAcquisitions.B69.value) - parseFloat(CreativeAcquisitions.B71.value);
CreativeAcquisitions.B76.value = parseFloat(CreativeAcquisitions.B17.value);
CreativeAcquisitions.D76.value = (parseFloat(CreativeAcquisitions.B76.value) * parseFloat(CreativeAcquisitions.C76.value)) / 100;
CreativeAcquisitions.B77.value = parseFloat(CreativeAcquisitions.B19.value);
CreativeAcquisitions.D77.value = (parseFloat(CreativeAcquisitions.B77.value) * parseFloat(CreativeAcquisitions.C77.value)) / 100;
CreativeAcquisitions.B78.value = parseFloat(CreativeAcquisitions.B21.value);
CreativeAcquisitions.D78.value = (parseFloat(CreativeAcquisitions.B78.value) * parseFloat(CreativeAcquisitions.C78.value)) / 100;
CreativeAcquisitions.B79.value = parseFloat(CreativeAcquisitions.B23.value);
CreativeAcquisitions.D79.value = (parseFloat(CreativeAcquisitions.B79.value) * parseFloat(CreativeAcquisitions.C79.value)) / 100;
CreativeAcquisitions.B80.value = parseFloat(CreativeAcquisitions.B25.value);
CreativeAcquisitions.D80.value = (parseFloat(CreativeAcquisitions.B80.value) * parseFloat(CreativeAcquisitions.C80.value)) / 100;
CreativeAcquisitions.B81.value = parseFloat(CreativeAcquisitions.B76.value) + parseFloat(CreativeAcquisitions.B77.value) + parseFloat(CreativeAcquisitions.B78.value) + parseFloat(CreativeAcquisitions.B79.value) + parseFloat(CreativeAcquisitions.B80.value);
CreativeAcquisitions.D81.value = parseFloat(CreativeAcquisitions.D76.value) + parseFloat(CreativeAcquisitions.D77.value) + parseFloat(CreativeAcquisitions.D78.value) + parseFloat(CreativeAcquisitions.D79.value) + parseFloat(CreativeAcquisitions.D80.value);
CreativeAcquisitions.B91.value = parseFloat(CreativeAcquisitions.B36.value);
CreativeAcquisitions.B92.value = parseFloat(CreativeAcquisitions.B37.value);
CreativeAcquisitions.B93.value = parseFloat(CreativeAcquisitions.B38.value);
CreativeAcquisitions.B94.value = parseFloat(CreativeAcquisitions.B39.value);
CreativeAcquisitions.B95.value = parseFloat(CreativeAcquisitions.B40.value);
CreativeAcquisitions.B96.value = (parseFloat(CreativeAcquisitions.B52.value) * parseFloat(CreativeAcquisitions.B46.value)) / 100;
CreativeAcquisitions.B97.value = parseFloat(CreativeAcquisitions.B41.value);
CreativeAcquisitions.B98.value = (parseFloat(CreativeAcquisitions.B91.value) + parseFloat(CreativeAcquisitions.B92.value) + parseFloat(CreativeAcquisitions.B93.value) + parseFloat(CreativeAcquisitions.B94.value) + parseFloat(CreativeAcquisitions.B95.value) + parseFloat(CreativeAcquisitions.B96.value) + parseFloat(CreativeAcquisitions.B97.value)) * -1;
CreativeAcquisitions.C98.value = (parseFloat(CreativeAcquisitions.C91.value) + parseFloat(CreativeAcquisitions.C92.value) + parseFloat(CreativeAcquisitions.C93.value) + parseFloat(CreativeAcquisitions.C94.value) + parseFloat(CreativeAcquisitions.C95.value) + parseFloat(CreativeAcquisitions.C96.value) + parseFloat(CreativeAcquisitions.C97.value)) * -1;
CreativeAcquisitions.B101.value = parseFloat(CreativeAcquisitions.B4.value);
CreativeAcquisitions.B105.value = (parseFloat(CreativeAcquisitions.B101.value) * parseFloat(CreativeAcquisitions.B103.value)) / 100;
CreativeAcquisitions.B107.value = parseFloat(CreativeAcquisitions.C98.value);
CreativeAcquisitions.B108.value = parseFloat(CreativeAcquisitions.B101.value) - parseFloat(CreativeAcquisitions.B105.value) + parseFloat(CreativeAcquisitions.B107.value);
}

char counter doesn't work with paste event

I have written a code bellow for counting the character inside text box.
the code is working just fine the only problem with it is when i past a text into the text box i have to press any key so system start to count.
Could you please help me sort this problem
function GetAlhpa(text) {
var gsm = "#£$¥èéùìòÇØøÅåΔ_ΦΓΛΩΠΨΣΘΞ^{}\[~]|€ÆæßÉ!\"#¤%&'()*+,-./0123456789:;<=>?¡ABCDEFGHIJKLMNOPQRSTUVWXYZÄÖÑܧ¿abcdefghijklmnopqrstuvwxyzäöñüà";
var i = 0;
while (i <= String(text).length) {
if (gsm.indexOf(String(String(text).charAt(i))) == -1 && (String(text).charCodeAt(i) != 32) && (String(text).charCodeAt(i) != 27) && (String(text).charCodeAt(i) != 10) && (String(text).charCodeAt(i) != 13)) {
UniCodestring = " Unicode ";
Countsms = 70;
if ($('#SndSms_Message').val().length > 70)
Countsms = 67;
return;
}
i++;
}
Countsms = 160;
UniCodestring = "";
if ($('#SndSms_Message').val().length > 160)
Countsms = 153;
}
var Countsms = 160;
var UniCodestring = "";
var CounterSmsLen = 0;
var Two = "|^€{}[]~";
function GetCountSms() {
document.getElementById('SndSms_Message').addEventListener('input', function (e) {
var target = e.SndSms_Message,
position = SndSms_Message.selectionStart;
ConvertGreek();
CounterSmsLen = $('#SndSms_Message').val().length;
GetAlhpa($('#SndSms_Message').val());
var i = 0;
while (i < String(Two).length) {
var oldindex = -1;
while (String($('#SndSms_Message').val()).indexOf(String(String(Two).charAt(i)), oldindex) > -1) {
//if ( String($('#SndSms_Message').val()).indexOf(String(String(Two).charAt(i))) > -1){
CounterSmsLen += 1;
oldindex = String($('#SndSms_Message').val()).indexOf(String(String(Two).charAt(i)), oldindex) + 1;
console.log(i);
}
i++;
}
SndSms_Message.selectionEnd = position; // Set the cursor back to the initial position.
});
if ($('#SndSms_Message').val().length == 0)
CounterSmsLen = 0;
$('#SndSms_Count').html(' ' + CounterSmsLen + ' Characters' + UniCodestring + ' <br /> ' + Math.ceil(CounterSmsLen / Countsms) + ' Sms');
countsmsnumber=Math.ceil(CounterSmsLen / Countsms);
}
var greekchar = "ΑΒΕΖΗΙΚΜΝΟΡΤΥΧ";
var englishchar = "ABEZHIKMNOPTYX";
function ConvertGreek() {
var str = $('#SndSms_Message').val();
var i = 0;
while (i < String(greekchar).length) {
str = str.replace(new RegExp(String(greekchar).charAt(i), 'g'), String(englishchar).charAt(i));
i++;
}
$('#SndSms_Message').val(str);
P.S.
If i paste the number into the text box it will count it correct but if i paste character it wont count them..
You need keyup change event in order to handle paste event.
document.getElementById('SndSms_Message').addEventListener("keyup", function() {
//your code here
});
example

JavaScript While Loop Variable Returning NaN

I'm making a Numerology conversion web app with JavaScript and HTML5. I've ran into a strange issue with a variable and loops. Below is my whole project in its current form.
<html>
<body>
<h1>My First Numerology Project</h1>
<form>
Month:<br>
<input type="text" maxlength="2" name="userInputMonth" id='userInputMonth'>
<br>
Day:<br>
<input type="text" maxlength="2" name="userInputDay" id='userInputDay'>
<br>
Year:<br>
<input type="text" maxlength="4" name="userInputYear" id='userInputYear'>
<br><br>
First Name:<br>
<input type="text" name="userInputFirstName" id='userInputFirstName'>
<br>
Middle Name:<br>
<input type="text" name="userInputMiddleName" id='userInputMiddleName'>
<br>
Last Name:<br>
<input type="text" name="userInputLastName" id='userInputLastName'>
<br><br>
<input type="button" value="Calculate" name="Calculate" onclick="BirthDayCalculation()"/>
</form>
<p id="LLNResult"></p>
<br>
<p id="OPNResult"></p>
<br>
<p id="SNResult"></p>
<br>
<p id="PODNResult"></p>
<script type="text/javascript">
//Defined var
var LLNTemp1;
var LLNTemp2;
var LLNReduce1;
var LLNReduce2;
var NameTemp1;
var NameTemp2;
var OPNReduce1;
var OPNReduce2;
var SNReduce1;
var SNReduce2;
var PODNReduce1;
var PODNReduce2;
function BirthDayCalculation() {
var Reduction1 = 0;
var LLNReduceFinal2 = 0;
var Day = document.getElementById('userInputDay').value;
var Month = document.getElementById('userInputMonth').value;
var Year = document.getElementById('userInputYear').value;
var FirstName = document.getElementById('userInputFirstName').value;
var MiddleName = document.getElementById('userInputMiddleName').value;
var LastName = document.getElementById('userInputLastName').value;
var LLN = ("" + Day + Month + Year).toString();
var FullName = ("" + FirstName + MiddleName + LastName).toString().toUpperCase();
var FullNameLength = parseInt(FullName.length);
var LLNLength = parseInt(("" + Day + Month + Year).length);
var i = 0;
var LLNTemp2 = 0;
while (i < LLNLength) {
LLNTemp1 = parseInt(LLN.charAt(i));
LLNTemp2 += LLNTemp1;
i++;
}
if (LLNTemp2 > 9) {
var i = 0;
var a = parseInt(LLNTemp2.toString().length);
var LLNReduceFinal1 = 0;
var LLNTemp3String = LLNTemp2.toString();
while (i < a) {
LLNReduce1 = parseInt(LLNTemp3String.charAt(i));
LLNReduceFinal1 += LLNReduce1;
i++;
}
var LLNReduceFinal2 = 0;
var Reduction1 = LLNReduceFinal1;
if (LLNReduceFinal1 > 9) {
var i = 0;
var a = parseInt(Reduction1.toString().length);
var LLNTemp3String = Reduction1.toString();
while (i < a) {
LLNReduce1 = parseInt(LLNTemp3String.charAt(i));
LLNReduceFinal2 += LLNReduce1;
i++;
}
}
}
var OPN = 0;
var SN = 0;
var PODN = 0;
var PODNWhole = 0;
var i = 0;
while (i < FullNameLength) {
NameTemp1 = FullName.charAt(i);
var OPNTemp = 0;
var SNTemp = 0;
if (NameTemp1 == "A") SNTemp = 1;
if (NameTemp1 == "J" || NameTemp1 == "S") OPNTemp = 1;
if (NameTemp1 == "B" || NameTemp1 == "K" || NameTemp1 == "T") OPNTemp = 2;
if (NameTemp1 == "C" || NameTemp1 == "L") OPNTemp = 3;
if (NameTemp1 == "U") SNTemp = 3;
if (NameTemp1 == "D" || NameTemp1 == "M" || NameTemp1 == "V") OPNTemp = 4;
if (NameTemp1 == "E") SNTemp = 5;
if (NameTemp1 == "N" || NameTemp1 == "W") OPNTemp = 5;
if (NameTemp1 == "F" || NameTemp1 == "X") OPNTemp = 6;
if (NameTemp1 == "O") SNTemp = 6;
if (NameTemp1 == "G" || NameTemp1 == "P" || NameTemp1 == "Y") OPNTemp = 7;
if (NameTemp1 == "H" || NameTemp1 == "Q" || NameTemp1 == "Z") OPNTemp = 8;
if (NameTemp1 == "I") SNTemp = 9;
if (NameTemp1 == "R") OPNTemp =9;
OPN += OPNTemp;
SN += SNTemp;
PODNWhole += SNTemp;
PODNWhole += OPNTemp;
i++;
}
var PODN = PODNWhole
var OPNReduceFinal = 0;
if (OPN > 9) {
var OPNLength = parseInt(OPN.toString().length);
var OPNTempString = OPN.toString();
var i = 0;
while (i < OPNLength) {
OPNReduce1 = parseInt(OPNTempString.charAt(i));
OPNReduceFinal += OPNReduce1;
i++;
}
}
var SNReduceFinal = 0;
if (SN > 9) {
var SNLength = parseInt(SN.toString().length);
var SNTempString = SN.toString();
var i = 0;
while (i < SNLength) {
SNReduce1 = parseInt(SNTempString.charAt(i));
SNReduceFinal += SNReduce1;
i++;
}
}
var PODNReduceFinal = 0;
if (PODN > 9) {
var PODNLength = parseInt(PODN.toString().length);
var PODNTempString = PODN.toString();
var i = 0;
while (i < PODNLength) {
PODNReduce1 = parseInt(PODNTempString.charAt(i));
PODNReduceFinal += PODNReduce1;
i++;
}
// var PODNReduceFinal = PODNReduce2;
// var PODN = PODNReduce2;
}
var LLNResult = "Your Life Lesson Number Is:" + LLNTemp2 + "/" + Reduction1;
if (LLNReduceFinal2 != 0) {
LLNResult = LLNResult + "/" + LLNReduceFinal2;
}
var OPNResult = "Your Outer Personality Number is:" + OPN;
if (OPNReduceFinal != 0) {
var OPNResult = OPNResult + "/" + OPNReduceFinal;
}
var SNResult = "Your Soul Number is:" + SN;
if (SNReduceFinal != 0) {
var SNResult = SNResult + "/" + SNReduceFinal;
}
var PODNResult = "Your Path of Destiny Number is:" + PODNWhole;
if (PODNReduceFinal != 0) {
var PODNResult = PODNResult + "/" + PODNReduceFinal;
}
if (LLNTemp2 != 0) {
document.getElementById("LLNResult").innerHTML = LLNResult;
}
if (PODNWhole != 0) {
document.getElementById("OPNResult").innerHTML = OPNResult;
document.getElementById("SNResult").innerHTML = SNResult;
document.getElementById("PODNResult").innerHTML = PODNResult;
}
}
</script>
</body>
</html>
So basically you enter your birthday and full name into a form. the script will then convert the name to numbers A = 1, B = 2.... and reduce both to single digits. the numbers will be added one by one. example. 13=4, 55=10, 63=9.
Here is the general code used to make reductions. Let's make PODN = 55
var PODNReduceFinal = 0;
var PODN = 55;
if (PODN > 9) {
var PODNLength = parseInt(PODN.toString().length);
var PODNTempString = PODN.toString();
var i = 0;
while (i < PODNLength) {
PODNReduce1 = parseInt(PODNTempString.charAt(i));
PODNReduceFinal += PODNReduce1;
i++;
}
}
Currently, it only loops once but I would like to have it get reduced to the lowest number possible. 1 in this case. I was thinking that if I change the if to a while it would accomplish this but it doesn't work the way I thought it would. I tried to make some changes and got stuck in a loop. So I started to troubleshoot. I added another variable to prevent the whole loop from looping infinitely.
var PODNReduceFinal = 0;
var PODN = 55;
while (PODN > 9) {
var PODNLength = parseInt(PODN.toString().length);
var PODNTempString = PODN.toString();
var i = 0;
while (i < PODNLength) {
PODNReduce1 = parseInt(PODNTempString.charAt(i));
PODNReduce2 += PODNReduce1;
i++;
}
var PODNReduceFinal = PODNReduce2;
var PODN = PODNReduce2;
}
Using this I thought when PODN would be checked by the while loop first it would run through the first steps. Get the length of the number, in this case 2. Convert it to a string so it can pull the digits one by one. Pull the digits in sequence with the length of the loop and convert them to numbers. Add them together in PODNReduce2, 55=10. Set PODNReduceFinal = 10, set PODN = 10. Then return to the first condition and check that PODN is now 10 and is greater than 9. Loop again to reduce further. Doing this until it's a single digit stored in PODNReduceFinal. But that's not what happens. When I try to display PODNReduceFinal I get NaN. Even if I revert the first "while" to "if" it still doesn't work. I'm at a loss. Please help.

Too much recursion - radio button - jquery

I have a dynamic form and in that many fields I want to be autocalculated when user goes on with the form. In the form I have 2 radio button mrp and rate. By default mrp is selected. If user doesn't change the default button selected, the value totalCst will be calculated as qty*mrp*cstpercent of all the rows.
If user selects rate radiobutton the value will be calculated as qty*rate*cstpercent of all the rows. I'll add the onchange event later. First I want to get the value totalCst calculated on mrp only or rate whichever is selected.
Radio Button code -
<div class="form-group pull-right">
<label class="radio-inline"><input type="radio" name="taxon" id="mrp" value="mrp" checked="checked">MRP</label>
<label class="radio-inline"><input type="radio" name="taxon" id="rate" value="rate">Rate</label>
</div>
JS
<?php
/* start getting the total amount */
$this->registerJs('
function getSum() {
var sum = 0;
var totalDiscount = 0;
var totalMrp = 0;
var totalCst = 0;
var totalWbst = 0;
var totalCstonamount = 0;
var totalWbstonamount = 0;
var totalCstonmrp = 0;
var totalWbstonmrp = 0;
var cstperValue = $(".cstPercent").val();
var wbstperValue = $(".wbstPercent").val();
var selectedValue = $("input[name=taxon]:checked").val();
alert(selectedValue);
var items = $(".item");
items.each(function (index, elem) {
var qtyValue = $(elem).find(".qty").val();
var rateValue = $(elem).find(".rate").val();
var discValue = $(elem).find(".disc").val();
var mrpValue = $(elem).find(".mrp").val();
var freeValue = $(elem).find(".free").val();
sum = (parseFloat(sum) + (parseFloat(qtyValue) * parseFloat(rateValue))).toFixed(2);
totalDiscount = (parseFloat(totalDiscount) + ((parseFloat(qtyValue) * parseFloat(rateValue) * parseFloat(discValue))/100)).toFixed(2);
totalMrp = (parseFloat(totalMrp) + ((parseFloat(qtyValue) + parseFloat(freeValue)) * parseFloat(mrpValue))).toFixed(2);
totalCstonamount = (parseFloat(totalCst) + ((parseFloat(qtyValue) * parseFloat(rateValue)) * parseFloat(cstperValue))/100).toFixed(2);
totalWbstonamount = (parseFloat(totalWbst) + ((parseFloat(qtyValue) * parseFloat(rateValue)) * parseFloat(wbstperValue))/100).toFixed(2);
totalCstonmrp = (parseFloat(totalCst) + (((parseFloat(qtyValue) + parseFloat(freeValue)) * parseFloat(mrpValue)) * parseFloat(cstperValue))/100).toFixed(2);
totalWbstonmrp = (parseFloat(totalWbst) + (((parseFloat(qtyValue) + parseFloat(freeValue)) * parseFloat(mrpValue)) * parseFloat(wbstperValue))/100).toFixed(2);
});
if(isNaN(sum) || sum.length == 0) {
sum = 0;
}
if(isNaN(totalDiscount) || totalDiscount.length == 0) {
totalDiscount = 0;
}
if(isNaN(totalMrp) || totalMrp.length == 0) {
totalMrp = 0;
}
if(isNaN(totalCstonamount) || totalCstonamount.length == 0) {
totalCstonamount = 0;
}
if(isNaN(totalWbstonamount) || totalWbstonamount.length == 0) {
totalWbstonamount = 0;
}
if(isNaN(totalCstonmrp) || totalCstonmrp.length == 0) {
totalCstonmrp = 0;
}
if(isNaN(totalWbstonmrp) || totalWbstonmrp.length == 0) {
totalWbstonmrp = 0;
}
$(".sum").val(sum);
$(".totalDiscount").val(totalDiscount);
$(".totalMrp").val(totalMrp);
if (selectedValue == "mrp") {
getSum();
$(".totalCst").val(totalCstonmrp);
}
else if (selectedValue == "rate") {
getSum();
$(".totalCst").val(totalCstonamount);
}
}
$(".container-items").on("change", function() {
getSum();
});
$(".cstPercent").on("change", function() {
getSum();
});
$(".wbstPercent").on("change", function() {
getSum();
});
jQuery(".dynamicform_wrapper").on("afterDelete", function(e) {
getSum();
});
');
/*end getting the total amount */
?>
I'm getting the value selected in alert but too many popup and getting error -
Too much recursion
Updated JS
<?php
/* start getting the total amount */
$this->registerJs('
var totalCstonamount = 0;
var totalWbstonamount = 0;
var totalCstonmrp = 0;
var totalWbstonmrp = 0;
function getSum() {
var sum = 0;
var totalDiscount = 0;
var totalMrp = 0;
var totalCst = 0;
var totalWbst = 0;
// var totalCstonamount = 0;
// var totalWbstonamount = 0;
// var totalCstonmrp = 0;
// var totalWbstonmrp = 0;
var cstperValue = $(".cstPercent").val();
var wbstperValue = $(".wbstPercent").val();
//var selectedValue = $("input[name=taxon]:checked").val();
//alert(selectedValue);
var items = $(".item");
items.each(function (index, elem) {
var qtyValue = $(elem).find(".qty").val();
var rateValue = $(elem).find(".rate").val();
var discValue = $(elem).find(".disc").val();
var mrpValue = $(elem).find(".mrp").val();
var freeValue = $(elem).find(".free").val();
sum = (parseFloat(sum) + (parseFloat(qtyValue) * parseFloat(rateValue))).toFixed(2);
totalDiscount = (parseFloat(totalDiscount) + ((parseFloat(qtyValue) * parseFloat(rateValue) * parseFloat(discValue))/100)).toFixed(2);
totalMrp = (parseFloat(totalMrp) + ((parseFloat(qtyValue) + parseFloat(freeValue)) * parseFloat(mrpValue))).toFixed(2);
totalCstonamount = (parseFloat(totalCst) + ((parseFloat(qtyValue) * parseFloat(rateValue)) * parseFloat(cstperValue))/100).toFixed(2);
totalWbstonamount = (parseFloat(totalWbst) + ((parseFloat(qtyValue) * parseFloat(rateValue)) * parseFloat(wbstperValue))/100).toFixed(2);
totalCstonmrp = (parseFloat(totalCst) + (((parseFloat(qtyValue) + parseFloat(freeValue)) * parseFloat(mrpValue)) * parseFloat(cstperValue))/100).toFixed(2);
totalWbstonmrp = (parseFloat(totalWbst) + (((parseFloat(qtyValue) + parseFloat(freeValue)) * parseFloat(mrpValue)) * parseFloat(wbstperValue))/100).toFixed(2);
});
if(isNaN(sum) || sum.length == 0) {
sum = 0;
}
if(isNaN(totalDiscount) || totalDiscount.length == 0) {
totalDiscount = 0;
}
if(isNaN(totalMrp) || totalMrp.length == 0) {
totalMrp = 0;
}
if(isNaN(totalCstonamount) || totalCstonamount.length == 0) {
totalCstonamount = 0;
}
if(isNaN(totalWbstonamount) || totalWbstonamount.length == 0) {
totalWbstonamount = 0;
}
if(isNaN(totalCstonmrp) || totalCstonmrp.length == 0) {
totalCstonmrp = 0;
}
if(isNaN(totalWbstonmrp) || totalWbstonmrp.length == 0) {
totalWbstonmrp = 0;
}
$(".sum").val(sum);
$(".totalDiscount").val(totalDiscount);
$(".totalMrp").val(totalMrp);
// if (selectedValue == "mrp") {
// getSum();
// $(".totalCst").val(totalCstonmrp);
// }
// else if (selectedValue == "rate") {
// getSum();
// $(".totalCst").val(totalCstonamount);
// }
}
function getSumonclick(){
}
$(".container-items").on("change", function() {
getSum();
});
$(".cstPercent").on("change", function() {
getSum();
});
$(".wbstPercent").on("change", function() {
getSum();
});
getSum();
var selectedValue = $("input[name=taxon]:checked").val();
// var totalCstonamount = 200;
// var totalWbstonamount = 0;
// var totalCstonmrp = 100;
// var totalWbstonmrp = 0;
if (selectedValue == "mrp") {
getSum();
if(isNaN(totalCstonmrp) || totalCstonmrp.length == 0) {
totalCstonmrp = 0;
}
$(".totalCst").val(totalCstonmrp);
}
else if (selectedValue == "rate") {
getSum();
if(isNaN(totalCstonamount) || totalCstonamount.length == 0) {
totalCstonamount = 0;
}
$(".totalCst").val(totalCstonamount);
}
jQuery(".dynamicform_wrapper").on("afterDelete", function(e) {
getSum();
});
');
/*end getting the total amount */
?>
As per my understanding, Now the issue turns out to be to get the calculated values from inside of getSum function to outside of it.
First I want to get the value totalCst calculated on mrp only or rate
whichever is selected.
You can use the ternary operator here, rather than if... else...:
var factor = (factorMrp.checked ? 'mrp' : 'rate');
Working Example:
var factors = document.getElementById('factors');
var factorMrp = document.getElementById('mrp');
var factorRate = document.getElementById('rate');
var paragraph = document.getElementsByTagName('p')[0];
factorMrp.checked = true;
function checkFactor() {
var factor = (factorMrp.checked ? 'mrp' : 'rate');
paragraph.textContent = 'The value totalCst will be calculated as qty * ' + factor + ' * cstpercent of all the rows.';
}
factors.addEventListener('change',checkFactor,false);
window.addEventListener('load',checkFactor,false);
fieldset {
display: inline-block;
}
<form>
<fieldset id="factors">
<label class="radio-inline"><input type="radio" name="taxon" id="mrp" value="mrp" checked="checked">MRP</label>
<label class="radio-inline"><input type="radio" name="taxon" id="rate" value="rate">Rate</label>
</fieldset>
</form>
<p></p>

balancing two input number fields but not showing values in fields in jquery

<!--js-->
function changeValue(dropdown,source) {
var option = dropdown.options[dropdown.selectedIndex].value;
if (option == '1' && source==0) {
var total = 20;
$("span").text(total);
$('.balance').attr({"min":0, "max":total}).on('input', function() {
var value = parseInt(this.value);
var otherInputs = $('.balance').not(this);
var remainderDiv;
var remainder, sum;
if (isNaN(value)) {
value = 0;
} else if (value > total) {
value = total;
} else if (value < 0) {
value = 0;
}
this.value = value;
remainder = total - value;
remainderDiv = remainder / otherInputs.length;
sum = value;
$.each(otherInputs, function(input) {
sum += Number(otherInputs[input].value);
});
if (sum > total) {
otherInputs.val(remainderDiv);
}
});
}
else if (option == '2' && source==0) {
var total = 20;
$("span").text(total);
$('.balance').attr({"min":0, "max":total}).on('input', function() {
var value = parseInt(this.value);
var otherInputs = $('.balance').not(this);
var remainderDiv;
var remainder, sum;
if (isNaN(value)) {
value = 0;
} else if (value > total) {
value = total;
} else if (value < 0) {
value = 0;
}
this.value = value;
remainder = total - value;
remainderDiv = remainder / otherInputs.length;
sum = value;
$.each(otherInputs, function(input) {
sum += Number(otherInputs[input].value);
});
if (sum > total) {
otherInputs.val(remainderDiv);
}
});
}
<!--html-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select onchange="changeValue(this,0)">
<option value="1">1-person</option>
<option value="2">2-10 group</option>
</select>
<input type="number" class="balance">
<input type="number" class="balance">
<!--html-->
how would you do it that the remainder doesn't go in the input field two. but it should still minus from each other though when the user puts in a value. so if max =10. when the user inputs 5 in field one and puts zero in field two that would be correct. But if he puts 5 in field one and 6 in field two that would be incorrect. how could i do that using this code.
Update: Using a dropdown to control the global MAX variable:
var MAX = 1;
function changeMax(dropdown) {
switch (dropdown.selectedIndex) {
case 0:
MAX = 1;
break;
case 1:
MAX = 10;
break;
}
}
$('.balance').on('input', function() {
var inputs = $(".balance");
var currentInput = $(this);
var otherInput = null;
for (var i = 0; i < inputs.length; i++) {
if (!$(inputs[i]).is($(this))) {
otherInput = $(inputs[i]);
}
}
var currentValue = parseInt(currentInput.val(), 10);
var otherValue = parseInt(otherInput.val(), 10);
if (isNaN(otherValue)) {
otherValue = 0;
}
// disable entering "0000.."
if (isNaN(currentValue)) {
currentValue = 0;
currentInput.val(0);
}
// disable entering negative values
if (currentValue < 0) {
currentValue = 0;
currentInput.val(0);
}
var sum = currentValue + otherValue;
if (sum > MAX) {
var offset = sum - MAX;
currentInput.val(currentValue - offset);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select onchange="changeMax(this)">
<option value="1">1-person</option>
<option value="2">2-10 group</option>
</select>
<input type="number" class="balance">
<input type="number" class="balance">
I tried to keep it as simple as it can be.
MAX is set to 10. If you enter 2 on the first input, you can enter [0,1,2,3,4,5,6,7,8] on the other input. You can also enter negative values. If you don't want to, simply uncomment the commented part.
var MAX = 10;
$('.balance').on('input', function() {
var inputs = $(".balance");
var currentInput = $(this);
var otherInput = null;
for (var i = 0; i < inputs.length; i++) {
if (!$(inputs[i]).is($(this))) {
otherInput = $(inputs[i]);
}
}
var currentValue = parseInt(currentInput.val(), 10);
var otherValue = parseInt(otherInput.val(), 10);
if (isNaN(otherValue)) {
otherValue = 0;
}
/* if (currentValue < 0) {
currentValue = 0;
currentInput.val(0);
} */
var sum = currentValue + otherValue;
if (sum > MAX) {
var offset = sum - MAX;
currentInput.val(currentValue - offset);
}
});
<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">

Categories

Resources