The last days I read how NaN always compares false even with itself and how to compare stuff when NaN may occur, and now I made a JS that compares two NaN true. WTF? Or did I compare 'NaN' strings?
http://www.bksys.at/bernhard/JS-NaN-compare-true.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>radioactivity calculator</title>
</head>
<body>
<form name="form1">
a: <input type="text" name="a"><br>
b: <input type="text" name="b"><br>
x: <input type="text" name="x"><br>
</form>
<script type="text/javascript">
document.form1.a.value=Math.sqrt(-1);
document.form1.b.value=(1/0)/(1/0);
document.form1.x.value=(document.form1.a.value==document.form1.b.value);
</script>
</body>
</html>
You are indeed comparing the string "NaN" against another string "NaN", which equates to true. The value held in text input elements is always pulled as a String type.
A simple way to resolve this is to prefix your values with the Unary Plus (+) operator to convert them to integer values (you can drop those brackets, too):
document.form1.x.value = +document.form1.a.value == +document.form1.b.value;
Example
document.form1.a.value = Math.sqrt(-1);
document.form1.b.value = (1/0) / (1/0);
document.form1.x.value = +document.form1.a.value == +document.form1.b.value;
<form name="form1">
a: <input type="text" name="a" size="20" value="a"><br>
b: <input type="text" name="b" size="20" value="b"><br>
x: <input type="text" name="x" size="20" value="x"><br>
</form>
Note: As RobG pointed out in his comment below it's important to note here that converting the string value "NaN" to an integer with the Unary Plus operator converts it directly to NaN because the string cannot be replicated as a numeric value. The same would happen if both of your input elements contained the value "Foo" - or even contained two completely different non-numeric string values. Whilst this solution does work, it may yield undesired results if you are to extend this code to handle non-numeric values as well.
This is a JavaScript gotcha ;)
The proper way to compare NaN is to use the isNaN method.
var a = 'a' + 5; //NaN
if (isNaN(a)) {
//do something
}
NaN is a special value in JavaScript. It doesn't even equal itself (also a quick way to test):
var a = parseInt('seven');
if (a == a) {
alert("a == a");
} else {
alert("a != a"); // This will happen
}
if (a == 'NaN') {
// Won't happen
} else {
alert("NaN is not equal to the string 'NaN'"); // Here
}
http://jsfiddle.net/u951v90o/
Related
I have a small piece of code where I need to get the typeof value entered. Right now, i am getting only value entered in the box, but not the typeof. Can anyone help me here?
<p id="res">Value</p><input type="text" id="fname" name="fname"><br><br>
<script>
document.getElementById('fname').addEventListener('input', function(){
document.getElementById('res').textContent= this.value;
});
</script>
You need to use typeof keyword, and if you want to test number vs string then you need to do a check type by using isNaN and Number
I changed your function to arrow function
document.getElementById('fname').addEventListener('input', e => {
const value = e.currentTarget.value;
const checkType = isNaN(Number(value)) ? value : Number(value)
document.getElementById('res').textContent = typeof checkType
})
<p id="res">Value</p><input type="text" id="fname" name="fname"><br><br>
So typeof is not going to help you here. because the input is type="text" everthing typed into it will be casted to a string. exp: some types a 4, will be given to the js as "4". Im assuming you dont care about the type itself and just really want to know if they typed in a number. if thats the case, use the isNaN Function which will return false if a value can be casted to a number
isNaN("4") //false isNaN("hello") //true
PS: NaN stands for not a number
This question already has answers here:
How can val() return Number?
(5 answers)
Closed 11 months ago.
Given a number input:
<input type="number" id="create-y-small" name="create-y-small" value="0">
How do I get the value of the input as a number? The following returns a string:
$("#create-y-small").val()
Why is this the default behavior? Surely one should expect a number type input to give a number?
I've looked for answers elsewhere but no luck:
Input value is a string instead of a number -
Answers use parsing to parse to a number. I don't want to parse to a number I just want to get the number as a number.
Get variable value from input number - OP seemed happy to get the value as a string
Get the value of a input number in jQuery - Same story
https://www.codegrepper.com/code-examples/javascript/how+to+get+the+value+of+input+number+using+jquery - Same story
You can use jQuery's valHooks to change how jQuery returns values.
$.valHooks.number = {
get: function( elem ) {
return elem.value * 1;
}
};
You only need to do this once in your code and then all type=number inputs will instead return a number.
console.log(
"num is a string",
$("#num").val() === "1",
$("#num").val() === 1,
$("#txt").val() === "1",
$("#txt").val() === 1)
$.valHooks.number = {
get: function( elem ) {
return elem.value * 1;
}
};
// confirm no neffect on type='text'
console.log(
"num is a number",
$("#num").val() === "1",
$("#num").val() === 1,
$("#txt").val() === "1",
$("#txt").val() === 1)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type='number' id='num' value="1">
<input type='text' id='txt' value="1">
All input elements in HTML return a string as their value. If you want the result as an int, you have to convert it.
parseInt($("#create-y-small").val())
On my webpage there is an input box that should only allow user to enter a positive int/float number (i.e. 1234, 123.4, 12.34, 1.234 should all be allowed).
To make sure the value is valid, I have a function to validate the value before sending it to the server:
function isPositiveFloat(s){
return String(Number(s)) === s && Math.floor(Number(s)) > 0;
}
The function works great expect for one scenario: isPositiveFloat(1.0) will return false, as it turns out Number(1.0) will convert it to 1, therefore made the validation failed.
Any suggestions on how should I resolve this issue? Is using regex the only way to go?
Thanks in advance for any help!
You just need to use !isNaN(s)along with Number(s)>0:
function isPositiveFloat(s) {
return !isNaN(s) && Number(s) > 0;
}
Demo:
function isPositiveFloat(s) {
return !isNaN(s) && Number(s) > 0;
}
<input type="text" onchange="console.log(isPositiveFloat(this.value))" />
You can check on the MDN reference of isNaN() examples that:
isNaN('37.37'); // false: "37.37" is converted to the number 37.37 which is not NaN
So as you can see it will be working in your case with float numbers.
I use the following code:
<html>
<head>
<script type="text/javascript">
function asd(){
var b = document.getElementById("txt").value;
var c = document.getElementById("txt2").value;
if( b > c ){alert("The first value more than the second value");}
}
</script>
</head>
<body>
<textarea id="txt"></textarea>
<input type="button" value="Click me" onclick=asd()>
<br>
<textarea id="txt2"></textarea>
</body>
</html>
But the codes work incorrectly.
I am writing the firs textarea, 5.
I'm writng the scnd textarea , 40.
And alarm works. ı dont understand. I searched and find solution.
if( parseInt(b,10)) > (parseInt(c,10)) )
So why has failed the first time?
You're missing quotation marks around the method
<html>
<head>
<script type="text/javascript">
function asd(){
var b = document.getElementById("txt").value;
var c = document.getElementById("txt2").value;
if( b > c ){
alert("The first value more than the second value");
}
}
</script>
</head>
<body>
<textarea id="txt"></textarea>
<input type="button" value="Click me" onclick="asd()">
<br>
<textarea id="txt2"></textarea>
</body>
</html>
It failed the first time because the numbers are parsed as strings.
var b = document.getElementById("txt").value; //b = "5"
var c = document.getElementById("txt2").value; // c = "40"
if( b > c ){ // "5" > "40" is false because the browser will not understand this.
alert("The first value more than the second value");
}
If you use parseInt the strings will be parsed as an integer.
So:
var b = document.getElementById("txt").value; //b = "5"
var d = parseInt(b); // d = 5
The 'is greater/less than' sign will only work with integers ( and floats etc.) but not with strings. That's why the if-statement returned false.
Your code isn't working because you are storing a string. This is why you can't compare them correctly. You need to convert them into integer data types before you can compare them or perform arithmetic operations.
function asd(){
var b = document.getElementById("txt").value;
var c = document.getElementById("txt2").value;
if( parseInt(b) > parseInt(c) ){alert("The first value more than the second value");}
}
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt
The parseInt function converts its first argument to a string, parses it, and returns an integer or NaN. If not NaN, the returned value will be the decimal integer representation of the first argument taken as a number in the specified radix (base). For example, a radix of 10 indicates to convert from a decimal number, 8 octal, 16 hexadecimal, and so on. For radices above 10, the letters of the alphabet indicate numerals greater than 9. For example, for hexadecimal numbers (base 16), A through F are used.
If parseInt encounters a character that is not a numeral in the specified radix, it ignores it and all succeeding characters and returns the integer value parsed up to that point. parseInt truncates numbers to integer values. Leading and trailing spaces are allowed.
My first day of Javascript and I am incredibly confused. I am passing numbers returned from a form to a function, but the result is not consistent with what it should be. My testing leaves a lot to be desired, but hopefully the following makes sense.
The function g calculates the sum of the sequence.
<form name="gaussform">
<input name="min"
type="number"
min="1"
value="1">
<input name="max"
type="number"
min="2"
value="10">
<input name="step"
type="number"
min="1"
value="1">
<input onclick="alert_g()"
type="submit"
value="calculate">
</form>
<script type="text/javascript">
function g(min,max,step) {
var actualmax = max - ((max - min) % step)
return (min + actualmax) * ((1 + ((actualmax - min) / step)) / 2)
}
function alert_g() {
var frm = document.forms["gaussform"]
var min = frm["min"].value
var max = frm["max"].value
var step = frm["step"].value
if (min == 1) {
alert("min is 1")}
if (max == 10) {
alert("max is 10")}
if (step == 1) {
alert("step is 1")}
alert(g(min,max,step))
// below returns the desired result
alert(g(1,10,1))}
</script>
the if statements are only so I can understand what is going on!
So if the user enter 1,10,1 (the default values) the result should be 55.
alert(g(1,10,1)) -> 55
alert(g(min,max,step) -> 550
alert(g(1,100,2)) -> 2500
alert(g(min,max,step) -> 4975 (obviously min,max,step == 1,100,2)
the function g is correct, but I do not understand what is happening to the values that are being passed to it.
This expression...
min + actualmax
...is the problem.
You probably want to make that...
+min + +actualmax
...or use parseFloat(), parseInt() or whatever suits your requirements to turn those strings into an actual Number.
jsFiddle.
JavaScript's + operator is overloaded for arithmetic addition and string concatenation. Because user input is always a string, you're doing string concatenation.
The values you use in your function are strings (every value returned by a form will be a string). You need to convert them to number to get the good result. This can be done with parseFloat function.
parseFloat('5') // return 5
parseInt can also be used if you want an Integer (no floating point number e.g.: 1.3), but be sure to set the radix parameter in order to always get consistent results.
parseInt('5', 10) // return 5
This can be confusing because Javascript use the + symbol for addition and concatenations of strings (which is . sign in PHP for example). As so, it's hard for the javascript engine to know how a value is expected to be converted.
By the way, you can always use typeof operator to checkout the type of a variable. For example:
typeof '5' // ouput: String
typeof 5 // output: Number
alert(g(parseInt(min),parseInt(max),parseInt(step))) has solved it!
But apparently this is bad form. See comments...
alert(g(parseInt(min,10),parseInt(max,10),parseInt(step,10))) perhaps?