parseInt always returns NaN? - javascript

long story short, i was trying to validate a phone field. ive added
the isNaN and parseInt for checking the " " in the field but that said
This below never validates to true..what am i missing?
if(isNaN(parseInt(phone))){
error.text("Sorry but this phone field requires numbers only");
return false;
} else {
return true;
}
it always fails...it never reads true even when i enter a number in the field and submit.
i always get the error mssg.
EDIT: I am testing input values from a form, phone is the name of the field.

Various ways to coerse JS strings to numbers, and their consequences:
(source: phrogz.net)
I personally use *1 as it is short to type, but still stands out (unlike the unary +), and either gives me what the user typed or fails completely. I only use parseInt() when I know that there will be non-numeric content at the end to ignore, or when I need to parse a non-base-10 string.
Edit: Based on your comment, if using phone.val() fixed it then
You were using jQuery (which you never mentioned, and should have), and
You actually had/have a jQuery object, wrapping one or more DOM elements (probably just one).
Whenever you do var foo = $('…'); then the foo variable references a jQuery object of one or more elements. You can get the first actual DOM element from this via var fooEl = foo[0]; or var fooEl = foo.get(0);…but even then you still have a DOM element and not a particular property of that.
For form inputs, you need to get the .value from the DOM element, which is what the jQuery .val() method does.

parseInt is a bit odd at times:
> parseInt("123-456-789")
123
Fortunately you can probably solve your case with:
> Number("123-456-789")
NaN

parseInt only returns NaN if the first character cannot be converted to a number.
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/parseInt

I've seen Number() suggested, but that will still allow things like -21 or 123.456. The best way to check for the absence of non-digits in a string is like this:
function hasNonDigit(str){
return /\D/g.test(str.toString());
}
console.log(hasNonDigit("123-456-7890"));
console.log(hasNonDigit("1234567890"));

Related

+document.getElementByClassName('balance') returning NaN even though value on website in a number

Im making a script on in the console. And when i try use the command +document.getElementByClassName('balance') it returns NaN. The element im trying to get is a number and in the inspect element it looks like this -->
<span class="amount">0</span>
Does anyone have any ideas to get this element to return as a number.
Thanks!
First of all it's getElementsByClassName, but even then you can't just convert an HTMLSpanElement object to a number and expect it to work.
+document.getElementsByClassName('amount')[0].textContent
This will get the element, assuming it's the first one with that class name (you'd be better off with an ID really), gets its text content ("0") and converts it to a number.

.length property change inside a .substr()?

Here is some I just noticed and im asking if its normal. Im using a .length property inside a .substr(), but it seems like the value of .length change during the .substr(). Here is a example here : https://jsfiddle.net/L11yg3y0/1/
var immastring = "Metaphysics"
var test = immastring.substr(2,immastring.length-2);
alert(test);
Shouldn't it output "taphysi" instead of "taphysics"? Because right now, it means that in the method .substr, they first remove the first two character, actualize the .length value and then remove the last two character.
I was just wondering because I already used this kind of method in other language like c++ and c#, but it wasn't working that way.
.substr takes the start index and the length of the substring. "Metaphysics" has length 11, so immastring.length - 2 is 9. "taphysics".length is indeed 9.
If you want to specify the end index, use .substring instead.
JavaScript has two substring methods, you picked the wrong one.
str.substr(start[, length])
vs
str.substring(indexStart[, indexEnd])
References:
MDN substr
MDN substring

jQuery, how to test of a variable is a text node, containing no markup?

http://jsfiddle.net/DerNalia/zrppg/8/
I have two lines of code that pretty much do the same thing
var doesntbreak = $j("hello");
var breaks = $j(" ");
​The first one doesn't error, but the second one throws this
Syntax error, unrecognized expression:
should'nt they both behave the same?
any insight as to how to solve this?
in the actual method I'm using, ele is from the Dom, so it could eb a text node, or any other kind of node.
UPDATE:
the input to the function that I'm using that I noticed this takes selection from the dom.
updated example: http://jsfiddle.net/DerNalia/zrppg/11/ <- includes html markup.
So, I guess, my question is, how do I test if something is JUST a text node? and doesn't contain any markup?
In general, you cannot create standalone text nodes with the jQuery function. If a string isn't obviously HTML, it gets treated as a selector, and is not recognized by jQuery as a valid selector.
Assuming you want to parse arbitrary strings (which may have HTML tags or not), I suggest something like var result = $('<div></div>').html(' ').contents();. Place your your HTML or text string in a div to parse it and then immediately extract the parsed result as a jQuery object with the list of elements. You can append the resultant list of elements with $(parentElem).append(result);
try this:
function isTextNode(node){
div=document.createElement('div');
div.innerHTML=node;
return $(div).text()==$(div).html();
}
And " " is'nt a valid selector if you want to find a elements containing some text you must use the :contains selector http://api.jquery.com/contains-selector/
Internet Explorer (older versions at least) don't have built in "querySelector" functions, so the Sizzle engine has to do the work directly. Thus, the slightly different tolerances for bogus input can cause differences in error reporting.
Your selector expression " " is equally invalid in all browsers, however. The library is not obliged to quietly accept anything you pass it, so perhaps you should reconsider your application design.
If you want to check for entities, you could use a regular expression if you're confident that it's just a text node. Or you could get the contents with .text() instead of .html().
So, I have to thank Apsillers and Rolando for pointing me in the right direction. Their answers were very close, but gave me the information I needed.
This is what I ended up using:
TEXT_NODE = 3;
objectify = function(n) {
return $j("<div></div>").html(n).contents();
}
function textOnly(n) {
var o = objectify(n);
for (var i = 0; i < o.length; i++) {
if (objectify(o[i])[0].nodeType != TEXT_NODE) {
return false
}
}
return true;
}
And here is a jsFiddle with some test cases, that neither of the original code submissions passed.
to pass, it needed to handle this kind of input
"hello" // true
"hello<b>there</b>" // false
"<b>there</b>" // false
" " // false
Not actual answer, but may help someone with similar issue as mine and loosely related to this question. :)
I was getting same issue today, so fixed by removing
Changed:
var breaks = $j(" ");
to:
var breaks = $j(" ".replace(/&.*;/g, ""));
Here I am removing , < etc...
Note: value at is dynamic for me, so it can be anything.

Why check for !isNaN() after isFinite()?

I came across the goog.math.isFiniteNumber function in the Google Closure Library. What it does is checking whether a given number is both finite and not NaN.
The underlying code is:
goog.math.isFiniteNumber = function(num) {
return isFinite(num) && !isNaN(num);
};
So, first it checks whether the number is finite using the native isFinite function, and then does an additional check to make sure the number isn't NaN using isNaN.
However, isFinite already returns false in case the argument is NaN. So, what advantages does the check for isNaN provide?
The only difference is this:
!isNan(1/0) // --> true
isFinite(1/0) // --> false
isNaN checks whether the argument is a number or not. The Infinities (+/-) are also numerical, thus they pass the isNaN check, but don't pass the isFinite check.
** Note that any string which can be parsed as a number ("2", "3.14") will cause isNaN to return false.
Hope this helps.
PS: The answer given by user1170379 was very nearly perfect.
you might reason out [Why?] after reading this:
NaN doesn't check if the passed value is infinite or not - it checks if the input val evaluates into a "Type: Number" end-result. Because isNaN(string) is accepted, so the: isNaN("3.14") //false (which means true, the given token is duck converted into a type Number successfully )
You may understand that the input value may happen to be an unresolved brute number, even a math operation as simple as:
(x/y); which in turn might yield a (+/-infinity) number.
Here x=1, y=0; meaning (1/0).Then isNaN(x/y) will first evaluate to isNaN(1/0); then to
isNaN(infinity) //false. Since (1/0)=infinity is of type: "number" ie typeof(1/0) //"number" isNaN should and will return false.
You don't want to put "infinity" where an end result number is expected.
Probably for the same reason that I have implemented (isfinite(num) && isfinite(-num)) - I was getting errors from mysql complaining about putting "-nan" into the database even though I had a check for isfinite(field)...
A useful article on this subject is http://jacksondunstan.com/articles/983 which provides an optimization ((d*0.0)==0.0)
isNaN() returns true if the argument is not a number or if the argument is a non-numeric value such as a string or an object.Otherwise, It returns false.
Example: isNaN(0/0) =>true;
isNaN(2-1) =>false;
isFinite() returns true if the argument is a number other than NaN,Infinity or -Infinity.Otherwise, It returns false.
Example: isFinite("2000") =>false;
isFinite(200/2) =>true;`
If isFinite worked the way isFiniteNumber did, then there would be no reason to write isFiniteNumber. There's probably some browser out there somewhere that treats NaN as finite.

vb.net passing a value of text box in javascript function

MotherTongueTxtBox.Attributes.Add("onblur","val_Length(MotherTongueTxtBox.text,"hi friends",Length);")
in the above statement val_length s a javascript function in tat function the first parameter shd b the contents of the text box ,the second parameter s a string type,
is the statement correct i think it s wrong can u suggest a correct valid statement please
I had a little trouble understanding your question, but I think you're asking that the first parameter be the textbox text, and the second be the length of the textbox text. This I think should work:
MotherTongueTxtBox.Attributes.Add("onblur","val_Length(this.value,this.value.length)");
Remember that the above will render the html like:
<input type="text" onblur="val_Length(this.value, this.value.length)" />
In your original statement, the resulting (incorrect) html would have been something like:
<input type="text" onblur="val_Length(,0)"/>
Since MotherTongueTxtBox.Text and .Length would have been string.empty and 0 respectively (unless it already had initial values...)
EDIT:
Thanks for marking as solution. Just as a side note, one thing you may want to consider, is you don't need to pass this.value.length in as a parameter, since you're already passing in this.value. You could determine the length within your function. Just an idea though like this:
MotherTongueTxtBox.Attributes.Add("onblur","val_Length(this.value, 'Hi')");
And then in your javascript function:
function val_Length(value, myString) {
var length = value.length;
....
}

Categories

Resources