Restrict input field - javascript

How to I restrict a number entering into input field (numeric) greater than another number using JavaScript?
I used:
function numberalert(e) {
var matrictotal = document.getElementById("matrictotal").value;
var matricobtained = document.getElementById("matricobtained").value;
var intertotal = document.getElementById("intertotal").value;
var interobtained = document.getElementById("interobtained").value;
var bachelortotal = document.getElementById("bachelortotal").value;
var bachelorobtained = document.getElementById("bachelorobtained").value;
var mphilltotal = document.getElementById("mphilltotal").value;
var mphillobtained = document.getElementById("mphillobtained").value;
if (matricobtained > matrictotal || interobtained > intertotal || bachelorobtained > bachelortotal || mphillobtained > mphilltotal) {
alert("pleses provide obtained marks less then total marks");
e.returnValue = false;
e.preventDefault();
} else {
return true;
}
}
But after alert it allows number place in input field.

First, just get the object that represents each object then pass in the two methods into a helped method to do the actual comparison. If the values are not what you are looking for, then set the objects value to "" and highlight the textbox to show which one is wrong.
function numberalert(e) {
var matrictotal = document.getElementById("matrictotal");
var matricobtained = document.getElementById("matricobtained");
var intertotal = document.getElementById("intertotal");
var interobtained = document.getElementById("interobtained");
var bachelortotal = document.getElementById("bachelortotal");
var bachelorobtained = document.getElementById("bachelorobtained");
var mphilltotal = document.getElementById("mphilltotal");
var mphillobtained = document.getElementById("mphillobtained");
checkValue(matrictotal, matricobtained);
checkValue(intertotal, interobtained);
checkValue(bachelortotal, bachelorobtained);
checkValue(mphilltotal, mphillobtained);
}
function checkValue(total, obtained){
if (obtained.value > total.value) {
alert("Please provide obtained marks less then total marks: " + obtained.id);
obtained.value = "";
obtained.classList.add("error");
} else {
obtained.classList.remove("error");
return true;
}
}
.error {
border: 2px solid #FF0000;
}
<label for="matrictotal">matrictotal</label>
<input type="text" id="matrictotal" value="10">
<label for="matricobtained">matricobtained</label>
<input type="text" id="matricobtained" value="10">
<br />
<label for="intertotal">intertotal</label>
<input type="text" id="intertotal" value="10">
<label for="interobtained">interobtained</label>
<input type="text" id="interobtained" value="10">
<br />
<label for="bachelortotal">bachelortotal</label>
<input type="text" id="bachelortotal" value="10">
<label for="bachelorobtained">bachelorobtained</label>
<input type="text" id="bachelorobtained" value="10">
<br />
<label for="mphilltotal">mphilltotal</label>
<input type="text" id="mphilltotal" value="10">
<label for="mphillobtained">mphillobtained</label>
<input type="text" id="mphillobtained" value="10">
<button onclick=numberalert(this)>Check values</button>

Note : In Javascript there is no strictly greater than or strictly less than comparator .
In case if you need strictly greater than use
(a !==b && a > b) (or) (!(a < b))
Similarly for strictly less than use
(a !== b && a < b) (or) (!(a>b))
var toCheckNumber = 100;
validate = function(el, event) {
var errorText = document.getElementById('errorText');
errorText.innerHTML = "";
var x = event.which;
var value = el.value;
var number = 0;
switch (x) {
case 48: number =0;break;
case 49: number = 1; break;
case 50: number = 2; break;
case 51: number = 3; break;
case 52: number = 4; break;
case 53: number = 5; break;
case 54: number = 6; break;
case 55: number = 7; break;
case 56: number = 8; break;
case 57: number = 9; break;
case 8: number = -1; break;
case 46: number = -1; break;
default : event.preventDefault(); return ;
}
var tempval = (number !== -1) ? value * 10 + number : value;
if (!(tempval < toCheckNumber)) {
event.preventDefault();
errorText.innerHTML = "Enter number less than " + toCheckNumber;
}
}
<input type="number" onkeydown="validate(this,event)" onchange="document.getElementById('errorText').innerHTML=''">
<div id="errorText" style="color:red"></div>

Related

How to show values from a .js file previously executed from a webpage to another webpage?

This is the webpage that will execute calculations in JS there are other personalityType I just didn't include them
<div class="question">
<div>40. It is easy for me to identify how I feel and why. </div>
<div> <input class="radiobutton" type="radio" name="m40" value="0" personalityType="intrapersonal"> Never <input class="radiobutton" type="radio" name="m40" value="1" personalityType="intrapersonal"> Rarely <input
class="radiobutton" type="radio" name="m40" value="2" personalityType="intrapersonal"> Often
<input class="radiobutton" type="radio" name="m40" value="3" personalityType="intrapersonal"> Always
</div>
<div class="question">
<div>35. English is/was one of my favorite subjects in school. </div>
<div> <input class="radiobutton" type="radio" name="m35" value="0" personalityType="verbal"> Never <input class="radiobutton" type="radio" name="m35" value="1" personalityType="verbal"> Rarely <input class="radiobutton"
type="radio" name="m35" value="2" personalityType="verbal">
Often
<input class="radiobutton" type="radio" name="m35" value="3" personalityType="verbal"> Always
</div>
<div>
<a class="myButton" onclick=calculateScores() href=results.html>Get Results</a>
</div>
This is the .js
var bodilyScore = 0;
var mathematicalScore = 0;
var naturalistScore = 0;
var interpersonalScore = 0;
var visualScore = 0;
var verbalScore = 0;
var intrapersonalScore = 0;
var musicalScore = 0;
function calculateScores() {
var button = document.getElementsByClassName("radiobutton");
var buttonLength = button.length;
musicalScore = 0;
bodilyScore = 0;
mathematicalScore = 0;
naturalistScore = 0;
interpersonalScore = 0;
visualScore = 0;
verbalScore = 0;
intrapersonalScore = 0;
for (var i = 0; i < buttonLength; i++) {
if (button[i].type === 'radio' && button[i].checked) {
var value = Number(button[i].value);
var type = button[i].getAttribute("personalityType");
switch (type) {
case "musical":
musicalScore += value;
break;
case "bodily":
bodilyScore += value;
break;
case "mathematical":
mathematicalScore += value;
break;
case "naturalist":
naturalistScore += value;
break;
case "interpersonal":
interpersonalScore += value;
break;
case "visual":
visualScore += value;
break;
case "verbal":
verbalScore += value;
break;
case "intrapersonal":
intrapersonalScore += value;
break;
}
}
}
showResults();
}
function showResults() {
console.log(musicalScore);
console.log(bodilyScore);
console.log(mathematicalScore);
console.log(naturalistScore);
console.log(interpersonalScore);
console.log(visualScore);
console.log(verbalScore);
console.log(intrapersonalScore);
document.getElementById('musicalResult').innerText = musicalScore;
document.getElementById('bodilyResult').innerText = bodilyScore;
document.getElementById('naturalistResult').innerText = naturalistScore;
document.getElementById('interpersonalResult').innerText = interpersonalScore;
document.getElementById('visualResult').innerText = visualScore;
document.getElementById('intrapersonalResult').innerText = intrapersonalScore;
document.getElementById('verbalResult').innerText = verbalScore;
document.getElementById('mathematicalResult').innerText = mathematicalScore;
}
I wanted to get the value of the 3 highest scores among musicalScore, verbalScore, etc.). after clicking the "Get Results" button and display it on another webpage. How could I also attach a text to the Score with the highest value to be displayed also?
If you want to pass your result to another page you can store them in LocalStorage.
highestResults = {mathematicalScore: 4, naturalistScore: 6, verbalScore: 5};
localStorage.setItem('calculationResults', highestResults);
And on result page.
localStorage.getItem('calculationResults');
If you want to add text to highest result:
document.getElementById('mathematicalResult').innerText = mathematicalScore + ' - highest result';

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>

switch-case with many conditions

I'm using switch construction instead of if statement because I have more than one repeated statements where if statement doesn't wrong.
But it couldn't be calculated properly. Where am I wrong? The switch construction is not working. I used the console and the function sumUpNewCar worked right.
Therefore, I would like to execute all the sums in the box
function sprSelection() {
var sprCompleted = document.getElementById("sprCompleted");
var sprDoesntCompleted = document.getElementById("sprDoesntCompleted");
if(sprCompleted.checked) {
sprDoesntCompleted.disabled = true;
}
else if(sprDoesntCompleted.checked) {
sprCompleted.disabled = true;
}
else {
sprDoesntCompleted.disabled = false;
sprCompleted.disabled = false;
}
}
function prNewVehicleSelection (){
var twentyFiveCompleted = document.getElementById("twentyFiveCompleted");
var thirtyCompleted = document.getElementById("thirtyCompleted");
var thirtyFiveCompleted = document.getElementById("thirtyFiveCompleted");
if(twentyFiveCompleted.checked) {
thirtyCompleted.disabled = true;
thirtyFiveCompleted.disabled = true;
}
else if(thirtyCompleted.checked) {
twentyFiveCompleted.disabled = true;
thirtyFiveCompleted.disabled = true;
}
else if(thirtyFiveCompleted.checked) {
twentyFiveCompleted.disabled = true;
thirtyCompleted.disabled = true;
}
else {
twentyFiveCompleted.disabled = false;
thirtyCompleted.disabled = false;
thirtyFiveCompleted.disabled = false;
}
}
function sumUpNewCar(){
var promoLoan = Number (document.getElementById("promoLoan").innerHTML);
var standardLoan = Number (document.getElementById("newAuto2").innerHTML);
var promoPlusLoan = Number (document.getElementById("newAuto3").innerHTML);
var standardPlusLoan = Number (document.getElementById("newAuto4").innerHTML);
var twentyFiveCompleted = document.getElementById("twentyFiveCompleted");
var thirtyCompleted = document.getElementById("thirtyCompleted");
var thirtyFiveCompleted = document.getElementById("thirtyFiveCompleted");
var sprCompleted = document.getElementById("sprCompleted");
var sprDoesntCompleted = document.getElementById("sprDoesntCompleted");
var qualityCompleted = document.getElementById("qualityCompleted");
var qualityDoesntCompleted = document.getElementById("qualityDoesntCompleted");
var sumPromoLoansBonus = Number (document.getElementById("sumPromoLoansBonus").innerHTML);
var sumPromoPlusLoansBonus = Number (document.getElementById("sumPromoPlusLoansBonus").innerHTML);
var sumStandardLoansBonus = Number (document.getElementById("sumStandardLoansBonus").innerHTML);
var sumStandardPlusLoansBonus = Number (document.getElementById("sumStandardPlusLoansBonus").innerHTML);
var sumNewVehicle = Number (document.getElementById("sumNewVehicle").innerHTML);
switch(sumNewVehicle) {
case twentyFiveCompleted.checked:
sumPromoLoansBonus = Math.round (Number(promoLoan * 0.0155));
sumPromoPlusLoansBonus = Math.round (Number (promoPlusLoan * 0.0289));
sumStandardLoansBonus = Math.round (Number (standardLoan * 0.0321));
sumStandardPlusLoansBonus = Math.round (Number(standardPlusLoan * 0.0432));
break;
case thirtyCompleted.checked:
sumStandardLoansBonus = Math.round (Number (standardLoan * 0.0321));
sumStandardPlusLoansBonus = Math.round (Number(standardPlusLoan * 0.054321));
break;
case thirtyFiveCompleted.checked:
sumPromoLoansBonus= Math.round (Number(promoLoan * 0.01234));
sumPromoPlusLoansBonus = Math.round (Number (promoPlusLoan * 0.0321));
sumStandardLoansBonus= Math.round (Number (standardLoan * 0.066));
sumStandardPlusLoansBonus = Math.round (Number(standardPlusLoan * 0.7888));
break;
case sprCompleted.checked:
sumPromoLoansBonus = Math.round (Number(promoLoan * 0.01222));
sumPromoPlusLoansBonus = Math.round (Number (promoPlusLoan * 0.028989));
sumStandardLoansBonus = Math.round (Number (standardLoan * 0.02111));
sumStandardPlusLoansBonus = Math.round (Number(standardPlusLoan * 0.041111));
break;
case sprCompleted.checked && twentyFiveCompleted.checked:
sumStandardLoansBonus = Math.round (Number (standardLoan * 0.047868));
sumStandardPlusLoansBonus= Math.round (Number(standardPlusLoan * 0.056555));
break;
case sprCompleted.checked && thirtyFiveCompleted.checked:
sumPromoLoansBonus = Math.round (Number(promoLoan * 0.02222));
sumPromoPlusLoansBonus = Math.round (Number (promoPlusLoan * 0.0345));
sumStandardLoansBonus = Math.round (Number (standardLoan * 0.04445));
sumStandardPlusLoansBonus= Math.round (Number(standardPlusLoan * 0.0667);
break;
default:
sumPromoLoansBonus = Math.round (Number (promoLoan * 0.0015));
sumPromoPlusLoansBonus= Math.round (Number (promoPlusLoan * 0.0244));
sumStandardLoansBonus = Math.round (Number (standardLoan * 0.0244));
sumStandardPlusLoansBonus = Math.round (Number (standardPlusLoan * 0.03511));
break;
}
}
function calculate(){
var sumPromoLoansBonus = Number (document.getElementById("sumPromoLoansBonus").innerHTML);
var sumPromoPlusLoansBonus = Number (document.getElementById("sumPromoPlusLoansBonus").innerHTML);
var sumStandardLoansBonus = Number (document.getElementById("sumStandardLoansBonus").innerHTML);
var sumStandardPlusLoansBonus = Number (document.getElementById("sumStandardPlusLoansBonus").innerHTML);
var sumNewVehicle = document.getElementById("sumNewVehicle").innerHTML = Number (sumPromoLoansBonus + sumPromoPlusLoansBonus + sumStandardLoansBonus + sumStandardPlusLoansBonus );
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>revenue calculator Version 7</title>
</head>
<body>
<!--BOX #1-->
<div class="mainbox">
<form >
<input class="promo" type="number" min="1000" max="100000000" id="promoLoan" onchange="sumUpNewCar()">
<input class="standard" type="number" min="100000" max="100000000" id="newAuto2" onchange="sumUpNewCar()">
<input class="promoPlus" type="number" min="100000" max="100000000" id="newAuto3" onchange="sumUpNewCar()">
<input class="standardPlus" type="number" min="100000" max="100000000" id="newAuto4" onchange="sumUpNewCar()">
</form>
</div>
<!--BOX #2-->
<div class="mainbox2">
<label class="container4"><b>25%</b>
<input type="checkbox" class="input1" id="twentyFiveCompleted" onclick="prNewVehicleSelection(), sumUpNewCar(), calculate()">
</label>
<label class="container4"><b>30%</b>
<input type="checkbox" class="input1" id="thirtyCompleted" onclick="prNewVehicleSelection(), sumUpNewCar(), calculate()">
</label>
<label class="container4"><b>35%</b>
<input type="checkbox" class="input1" id="thirtyFiveCompleted" onclick="prNewVehicleSelection(), sumUpNewCar(), calculate()">
</label>
<label class="container" for="yes"><b> Да</b>
<input type="checkbox" class="input1" name="yes" id="sprCompleted" onclick="sprSelection(), sumUpNewCar()">
</label>
<label class="container" for="no"><b> Нет</b>
<input type="checkbox" class="input1" name="no" id="sprDoesntCompleted" onclick="sprSelection(), sumUpNewCar()">
</label>
<!--BOX#6-->
<div class="mainbox6">
<table class="tableOverall" >
<tr>
<td id="sumNewVehicle"></td>
</tr>
</table>
</div>
</div>
<table class="tableOverall2">
<tr>
<td id="sumPromoLoansBonus"></td> <!-- sum of promo box BASIC-->
<td id="sumPromoPlusLoansBonus"></td> <!-- sum of promoplus box BASIC-->
<td id="sumStandardLoansBonus"></td> <!-- sum of standard box BASIC-->
<td id="sumStandardPlusLoansBonus"></td> <!-- sum of standard plus box BASIC-->
</table>
What are the possible values that sumNewVehicle will has? It will return some number in your case.
Also what values that twentyFiveCompleted.checked will have? I guess it will give either True or False.
So if both these variables are having different values then your switch case will never work.
Secondly you are using "&&" condition in Switch case which is not accepted.
Even if twentyFiveCompleted.checked will return a Number then also due to "&&" condition in Switch case your switch case iteration won't work.
For example:- you are using
case sprCompleted.checked && twentyFiveCompleted.checked:
That is the case where you should use if clauses, instead of switch case.
It will work in JavaScript as long as your conditions return proper boolean values, but it doesn't have many advantages over else if statements.Your comparison value is an integer, but most of your case expressions resolve to a boolean value. Mainly those functions where you have used "&&" conditions.
Refer this link for more info
javascript: using a condition in switch case
I think you need to check out the switch Case syntax :
switch(expression) {
case n:
code block1
break;
case m:
code block 2
break;
default:
code block 3
}
which is equivelant to :
if (expression == n) {
code block 1
}
else if (expression == m) {
code block 2
}
else {
code block 3
}

change() jQuery not working

I'm having some trouble getting my change() event working in jQuery. I am making a small program that converts temperatures to Kelvin, and I want the span that holds my value after conversion to update 1) every time the temperature to convert changes and 2) every time a different temperature scale is selected from the radio buttons.
Relevant Code:
$(document).ready(function() {
$('input[type=radio]').checkboxradio();
var temp = parseFloat()
$('input.listener').change(function() {
var name = $(this).attr("name");
var val = $(this).val();
switch (name) {
case 'unit':
var temperature = $('input#temp').val();
switch (val) {
case 'f':
$('span#output').html(((temperature - 32) / 1.8) + 273.15);
break;
case 'c':
$('span#output').html(temperature + 273.15);
break;
case 'r':
$('span#output').html(temperature / 1.8);
break;
}
case 'temp':
var u = $('input[name=unit]:checked').val();
switch (u) {
case 'f':
$('span#output').html(((val - 32) / 1.8) + 273.15);
break;
case 'c':
$('span#output').html(val + 273.15);
break;
case 'r':
$('span#output').html(val / 1.8);
break;
}
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="widget">
<fieldset>
<legend>Select a Unit to Convert to Kelvin: </legend>
<label for="fRadio">Fahrenheit</label>
<input id="fRadio" class="listener" type="radio" name="unit" value="f">
<label for="cRadio">Celsius</label>
<input id="cRadio" class="listener" type="radio" name="unit" value="c">
<label for="rRadio">Rankine</label>
<input id="rRadio" class="listener" type="radio" name="unit" value="r">
</fieldset>
</div>
<h2>Temperature Converter</h2>
<p>Type a value in the Fahrenheit field to convert the value to Kelvin:</p>
<p>
<label>Temperature</label>
<input id="temp" class="listener" type="number" value="32">
</p>
<p>Kelvin: <span id="output"></span></p>
My guess is I'm making a pretty dumb small mistake, but I can't seem to figure it out. Thanks for any and all help, suggestions, and solutions.
Two mistakes with your code:
Forgetting breaks; for the parent switch statement.
Forgetting name="temp" on the temperature field.
I changed the final temperature to a variable and made that the text of the output just so that there would be so many $('span#output').html(temperature);
Also, you should use the oninput event to detect a change for the number field.
$(document).ready(function() {
//$('input[type=radio]').checkboxradio();
var temp = parseFloat();
$('input.listener').on('change', updateTemp);
$('input.listener').on('input', updateTemp);
function updateTemp() {
var name = $(this).attr("name");
var val = $(this).val();
var final;
switch (name) {
case 'unit':
var temperature = $('input#temp').val();
switch (val) {
case 'f':
final = ((temperature - 32) / 1.8) + 273.15;
break;
case 'c':
final = temperature + 273.15;
break;
case 'r':
final = temperature / 1.8;
break;
}
break;
case 'temp':
var u = $('input[name=unit]:checked').val();
switch (u) {
case 'f':
final = ((val - 32) / 1.8) + 273.15;
break;
case 'c':
final = val + 273.15;
break;
case 'r':
final = val / 1.8;
break;
}
break;
}
$("#output").text(final);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="widget">
<fieldset>
<legend>Select a Unit to Convert to Kelvin: </legend>
<label for="fRadio">Fahrenheit</label>
<input id="fRadio" class="listener" type="radio" name="unit" value="f">
<label for="cRadio">Celsius</label>
<input id="cRadio" class="listener" type="radio" name="unit" value="c">
<label for="rRadio">Rankine</label>
<input id="rRadio" class="listener" type="radio" name="unit" value="r">
</fieldset>
</div>
<h2>Temperature Converter</h2>
<p>Type a value in the Fahrenheit field to convert the value to Kelvin:</p>
<p>
<label>Temperature</label>
<input id="temp" class="listener" type="number" name="temp" value="32">
</p>
<p>Kelvin: <span id="output"></span></p>
You should set one of the radio buttons as default with checked="checked". Then try following:
$(document).ready(function () {
$('input.listener').change(function () {
if ($(this).attr("type") == 'radio') {
//radio button changed
var u = $(this).val();
} else {
var u = $("input[type='radio']:checked").val();
}
var temperature = $('#temp').val();
switch (u) {
case 'f':
$('span#output').html(((temperature - 32) / 1.8) + 273.15);
break;
case 'c':
$('span#output').html(temperature + 273.15);
break;
case 'r':
$('span#output').html(temperature / 1.8);
break;
}
});
});
You do not have break; after
case 'unit':
and when var name = "temp"
var val = $(this).val();
the value of var val above would be a number in string format, so when you do val + something in case 'temp' the number is getting appended instead getting added or substracted. Use parseInt(val) to convert the value of input box to integer in case of 'temp'.

Grand Total Calculation in Javascript to handle currency format (MinusSignNegative)

I currently have a javascript code below that calculates a grand total into a read only text field when dealing with currency formats i.e. $500.00. The problem that I am running into is how to handle the calculation when more than one negative number is entered in currency format (MinusSignNegative) i.e. ($500.00) instead of -$500.00. I am currently getting a NaN error in the grand total.
I believe that this regex should handle it but I can't figure out how to implement. http://www.regexlib.com/(X(1)A(bk8AHOFYowt7XHOC4WUCtfdM2LhlaovTNInhWLTrzAeoeq-c53XkkdwLD-WDe3OgQtJ7BLHSs0P-u-RrLbfVZaQIHkBH2exYGw0qtz6nqSamZNVqtnyufo9Y3nrEq5mq-mry63HY4Nnv0dfsQOZzKvuwcKAuwigyyQva-67laxr-ModxTQESW8fXx2XJL_0L0))/REDetails.aspx?regexp_id=625&AspxAutoDetectCookieSupport=1
Can anybody offer a solution?
<SCRIPT LANGUAGE="JavaScript">
<!--
function total(what,number) {
var grandTotal = 0;
for (var i=0;i<number;i++) {
if (what.elements['price' + i].value.replace(/\$|\,/g,'') == '')
what.elements['price' + i].value.replace(/\$|\,/g,'') == '0.00';
grandTotal += (what.elements['price' + i].value.replace(/\$|\,/g,'') - 0);
}
what.grandTotal.value = (Math.round(grandTotal*100)/100);
}
//-->
</SCRIPT>
<FORM NAME="myName">
Tax Due/Refund: <input TYPE="text" NAME="price0" VALUE="" SIZE="10" class='currency' onChange="total(this.form,3)"><BR>
Interest: <input TYPE="text" NAME="price1" VALUE="" SIZE="10" class='currency' onChange="total(this.form,3)"><BR>
Penalty: <input TYPE="text" NAME="price2" VALUE="" SIZE="10" class='currency' onChange="total(this.form,3)"><BR>
Total Amount Assessed: <INPUT TYPE="TEXT" NAME="grandTotal" class='currency' SIZE="25" READONLY="readyonly" style="background:#eee none; color:#222; font-weight:bold">
</FORM>
If you are trying to move a negative sign from the number to the left of a dollar sign,
do it when you write the total value field.
function total(what, number){
var grandTotal= 0, i= number, val, sign;
while(i){
val= what.elements['price' + i--].value.replace([$, ]+/g,'') ;
grandTotal+= parseFloat(val) || 0;
}
sign= grandTotal<0? '-' :'';
what.grandTotal.value= sign+'$'+ Math.abs(Math.round(grandTotal*100)/100);
}
You can do it with or without that regex.
Without:
fieldValue = field.value; // "(500.00)"
// search for a "(" char
if (fieldValue.indexOf("(") >= 0) {
// remove all chars, but numbers and dots
fieldValue = fieldValue.replace(/[^0-9.]/ig, "");
// 500.00
numberFieldValue = Number(fieldValue) * -1;
}
With:
fieldValue = field.value; // "(500.00)"
// test if the value matches that pattern for negative numbers
if (fieldValue.match(/PUT_THAT_REGEX_HERE/g)) {
// remove all chars, but numbers and dots
fieldValue = fieldValue.replace(/[^0-9.]/ig, "");
// 500.00
numberFieldValue = Number(fieldValue) * -1;
}
it should look like this:
function total(what,number) {
var grandTotal = 0;
for (var i=0;i<number;i++) {
fieldValue = what.elements['price' + i].value; // "(500.00)"
// search for a "(" char
if (fieldValue.indexOf("(") >= 0) {
// remove all chars, but numbers and dots
fieldValue = fieldValue.replace(/[^0-9.]/ig, "");
// 500.00
numberFieldValue = Number(fieldValue) * -1;
} else if (fieldValue.replace(/\$|\,/g,'') == '') {
numberFieldValue = 0;
} else {
numberFieldValue = number(fieldValue.replace(/\$|\,/g,''));
}
grandTotal += numberFieldValue ;
}
what.grandTotal.value = (Math.round(grandTotal*100)/100);
}

Categories