I'm working with the billing part of my system and I put an event in my TextBox using javascript and I have two textboxes. First is the cashonhand and change textboxes. But what I'm wondering is why the comparison between two textboxes is not giving me the right answer. Here is my code:
$(document).ready(function () {
$(document).on('click', '.btn-pay-bill', function () {
var cash = parseFloat(Number($('.cashonhand').val())).toFixed(2);
var amtdue = parseFloat(Number($('.amtdue').text())).toFixed(2);
if (cash <= amtdue) {
alert(cash + ' ' + amtdue + ' ' +"Insufficient Cash!!!");
return false;
}
if (cash >= amtdue) {
return true;
}
return false;
});
SO what am I missing here? Here is the output when I compare 100,000 to 78,200.00:
You're comparing alphabetically instead of numerically.
Note that .toFixed() returns a string:
Returns
A string representation of number that does not use exponential notation and has exactly digits digits after the decimal place.
You'll want to do this comparison before you call .toFixed()
var cash = parseFloat(Number($('.cashonhand').val()));
var amtdue = parseFloat(Number($('.amtdue').text()));
if (cash <= amtdue) {
alert(cash.toFixed(2) + ' ' + amtdue.toFixed(2) + ' ' +"Insufficient Cash!!!");
return false;
}
You can just call .toFixed() wherever you display the number in the UI, or create a separate string version of the value, such as sCash and sAmtDue or something.
Related
Working on a little task tracker applet that uses localstorage to both store tasks and keep a running tab of how many tasks have been created to date. The later is my issue.
Here's what I'm running, the issue is contained to variables "taskTracker" and "advanceTask".
function saveTask() {
var task = $("#task").val();
var taskDate = $("#taskDate").val();
if (newUser == null) {
var taskNumber = 0;
localStorage.setItem("taskTracker", "0");
localStorage.setItem("newUser", "no");
}
else {
var taskNumber = localStorage.getItem("taskTracker");
}
var advanceTask = taskNumber + 1;
localStorage.setItem('task' + taskNumber, task);
localStorage.setItem('task' + taskNumber + 'date', taskDate);
localStorage.setItem("taskTracker", advanceTask);
console.log(advanceTask);
displayTasks();
}
If you take a look at the "advanceTask" variable, my intention is to advance the numerical value stored in "taskTracker" each time this function is invoked. However, all I'm getting is an additional "1" appended to the value each time.
Thoughts? <3
There is a difference between string + number and number + number. Your current solution is like the stringPlusOne function below. You need to convert the string to a number (using parseInt is one way) and then do the math, like the stringPlusOne2 function below
function stringPlusOne(str) {
console.log(str + 1);
}
function stringPlusOne2(str) {
console.log(parseInt(str, 10) + 1);
}
stringPlusOne("2");
stringPlusOne2("2");
I have an anchor which I inject in HTML in jqGrid formatter as below:
var number = rowObject.number;
var plateNumber = rowObject.plateNmber;
var markup = "<a href=%Href%;>%Text%</a>"
var replacements = {
"%Text%": plateNumber ,
"%Href%": "javascript:Search.openViewByPlateNumber(" + number + "," + plateNumber + ")"
};
markup = markup.replace(/%\w+%/g, function(all) {
return replacements[all];
});
Here is my OpenViewByPlateNumber function:
var OpenViewByPlateNumber = function(number, plateNumber) {
// Do something
};
In the UI there will be a number in the grid. When I click on the number the openViewByPlateNumber function will be called. Everything is working fine for me. The problem is the plate number is a string type. It is a number but it can be 1, 2, 3/4, 340/2 etc.
It's working fine when number is simple like 1, 5 or 9 but if number is 340/2, then the method receives a value of 170.5. It divides the number. So how I can pass it as string?
To pass the values to the function as a string wrap them in quotes:
"%Href%": 'javascript:Search.openViewByPlateNumber("' + number + '","' + plateNumber + '")'
What I'm trying to do:
I have a javascript program that, when a button is clicked, takes in 4 strings from 4 text boxes in a form, and outputs those strings into a formatted textarea.
function testResults(form){
var errorhandle1 = parseInt(document.myForm.Item_Code.value);
var errorhandle2 = parseInt(document.myForm.Item_Cost.value);
var errorhandle3 = parseInt(document.myForm.Quantity.value);
//above variables are for error handling.
var d = " ";
var subtotal = parseInt(form.Item_Cost.value) * parseInt(form.Quantity.value);
var subtotalValue = parseInt(document.myForm.Subtotal.value);
var testVar = "Item Code: " + form.Item_Code.value + d +
"Item Name: " + form.Item_Name.value + d +
"Item Cost: " + form.Item_Cost.value + d +
"Quantity: " + form.Quantity.value + '\n';
document.myForm.myTextarea.value += testVar;
document.myForm.Subtotal.value = parseInt(subtotal) + subtotalValue;
document.myForm.Sales_Tax.value = document.myForm.Subtotal.value * salestax;
document.myForm.Total.value = parseInt(document.myForm.Subtotal.value) + parseFloat(document.myForm.Sales_Tax.value);
}
The above code works just fine, and does exactly what I want it to do for the scope of my program.
try {
if ((isNaN(errorhandle3) == true) || (isNaN(errorhandle2) == true)) {
throw "Error1";
}
} catch (e) {
if (e == "Error1") {
alert("Error! You must enter a number into the qty and cost fields!");
}
}
What I'm trying to accomplish with the try...catch block is simply to make sure that
document.myForm.Item_Code.value
document.myForm.Item_Cost.value
document.myForm.Quantity.value
are actually numbers.
The try...catch statements trigger every time I run the program and doesn't care what I put in the corresponding text boxes. I would greatly appreciate any and all insight on this!
Also: I looked at both of these links and was unable to understand my problem.
javascript parseInt return NaN for empty string
http://www.w3schools.com/jsref/jsref_isnan.asp
Your root problem here is that isNaN() tests to see if the value is NaN. It does not test to see if a string is a proper number. It has some coercion rules to try to deal with strings, but that really isn't what it is designed for.
You can see ways to test if something can be parsed into a valid number here: Validate decimal numbers in JavaScript - IsNumeric()
It's worth reading the detail in the good answers there, but it boils down to something like this which is a bit more than you need, but is general purpose:
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
And, then there's no reason to use exceptions in your code, so you can just do this:
if (!isNumber(errorhandle3) || !(isNumber(errorhandle2)) {
alert("Error! You must enter a number into the qty and cost fields!");
}
Also, in your code, some .Value properties look like maybe they should be .value (lowercase).
In your first code block
var errorhandle2 = parseInt(document.myForm.Item_Cost.Value);
var errorhandle3 = parseInt(document.myForm.Quantity.Value);
You are using Value, which should be value, that's case-sensitive.
By the way, isNaN returns boolean, you don't have to compare with true
My code in HTML takes a user input number in, and it does a calculation and then displays the output. The user chosen input is put into a formula and the result of the formula is added to the user input number, but when it adds the two number together it's adding a decimal spot.
For example, if the number 11 is chosen, the result of Rchange is 0.22, so .22 is then added 11 to be 11.22 for newResistance, but instead it is displaying the value as 110.22 instead.
function calc(form) {
if (isNaN(form.resistance.value)) {
alert("Error in input");
return false;
}
if (form.resistance.value.length > 32) {
alert("Error in input");
return false;
}
var Rchange = .01 * 2 * form.resistance.value;
var newResistance = (form.resistance.value + Rchange);
document.getElementById("newResistance").innerHTML = chopTo4(newResistance);
}
function chopTo4(raw) {
strRaw = raw.toString();
if (strRaw.length - strRaw.indexOf("0") > 4) strRaw = strRaw.substring(0, strRaw.indexOf("0") + 5);
return strRaw;
}
HTML DOM element properties are always strings. You need to convert them to numbers in your usage.
parseInt(form.resistance.value);
parseFloat(form.resistance.value);
+form.resistance.value;
(Any of the three will work; I prefer the first two (use parseInt unless you're looking for a float).)
Try newResistance = +form.resistance.value + Rchange;. This will convert it to a number.
It's because it's treating the values as a string.
form.resistance.value + Rchange are both strings, so it's appending it.
Use the parseInt JavaScript method to get the decimal version.
I'm calculating a total number. I get the sum values from div's. But in total, instead of numbers I get (NaN - Not a Number)
JavaScript Function:
<script type="text/javascript">
function calculateTotal(){
var total = document.getElementById('valor1').innerHTML*1 + document.getElementById('valor2').innerHTML*1 + document.getElementById('valor3').innerHTML*1 + document.getElementById('valor4').innerHTML*1 + document.getElementById('valor5').innerHTML*1 + document.getElementById('valor6').innerHTML*1;
document.getElementById('total').innerHTML = total;
}
</script>
EDIT:
I found the error, I had a closing tag inside the DIV's like this:
<center><div id="valor1"></center></div>
Changed to:
<center><div id="valor1"></div></center>
You cannot use document.getElementById('valor1').innerHTML directly. You have to convert this to number. Please try this.
var value = document.getElementById('valor1').innerHTML;
var number = parseFloat(value)||0;
Do this for each div innerHTML which have number.
var number = parseFloat(value)||0;
The above line will help you to assign 0 to value if div is empty or div html cannot be converted to a number.
Use parseFloat(document.getElementById('x').innerHTML) to convert them to numbers before performing operations:
var total = parseFloat(document.getElementById('x1').innerHTML) + parseFloat(document.getElementById('x2').innerHTML);
You also may want to check them if they're numeric, here's a simple test using isNaN:
alert((isNaN("23"))?'not number':'number');
HTML:
<div id="valor1">2</div>
<div id="valor2">2</div>
<div id="valor3">ccccc</div>
<div id="valor4">2</div>
<div id="valor5">2</div>
<div id="valor6">2</div>
<hr/>
<div id="total">0</div>
JavaScript:
function $(id) { return document.getElementById(id); }
function get(elem) { return parseFloat($(elem).innerHTML) || 0; }
(function() {
var total =
get('valor1') * 1 + get('valor2') * 1 + get('valor3') * 1 +
get('valor4') * 1 + get('valor5') * 1 + get('valor6') * 1;
$('total').innerHTML = total;
}());
A little optimization of the work and demo.
But why stop here? :) we can make it even better ( I think ):
function get(elem) {
return (parseFloat($(elem).innerHTML) || (function() {
$(elem).innerHTML += " <i>Not a number assumed 0</i>";
return 0;
}()));
}
And the updated demo.
Edit: no errors on Chrome & Mozilla (Linux).
try using parseInt() as in
var total = parseInt(document.getElementById('valor1').innerHTML)*1 + parseInt(document.getElementById('valor2').innerHTML)*1 + ... ;
etc etc
this will ensure that what you're getting out of the fields is in fact, a number
Did you try to put these parts into brackets?
(document.getElementById('valor1').innerHTML * 1) + ...
See: http://rx4ajax-jscore.com/ecmacore/operator/predence.html
Even better - use the parseInt(var string) function;
parseInt(document.getElementById('valor1').innerHTML) + ...