typeof command doesnt work - javascript

Hi I'm trying to check the value of DOM with:
if ($('#ATTN').val() == '') {
$('#ATTN').val(0);
} else {
iattn=$('#ATTN').val();
alert(iattn);
if(typeof iattn == 'number'){
alert('oh');
}
}
but it returns nothing. Also no error shown.

This line
iattn=$('#ATTN').val();
Returns a string.
If you want to see whether it can be converted to an integer, then what you want is this:
iattn=parseInt($('#ATTN').val());
if (iattn) {
alert("oh");
}
Use parseFloat rather than parseInt if you want a more general number test.
If you want to check that the result of parsing matches the input, use something like this:
iattn=$('#ATTN').val();
if (iattn == parseInt(iattn)) {
alert("oh");
}
A simpler check, which won't actually convert anything to a number, and will allow all number formats (eg 2.3, 0x3, +23) is this:
if (!isNaN(iattn)) {
alert("oh");
}
Credit to #p.s.w.g from a comment.

.val() return a DOMString(string)
so typeof iattn always will be a string
if you want the typeof number you need convert to int
using parseInt(iattn) or parseFloat(iattn)

Related

javascript isNaN() function not working?

I have a function to test if a prompt input is a number, like so:
function myFunction()
{
var person = prompt("Please enter your name", "");
if (person != null)
{
if(isNaN(person))
{
document.write("hello " + person + "<br><br>");
}
else
document.write("You gave me a number");
}
else
{
document.write("You didn't answer.<br><br>");
}
}
but every time I enter a number it keeps outputting hello + the number. I've been googling this function for quite some time and it doesn't make sense to me, it seems like it should work. Why is person returning true?
NaN is a special value in Javascript. What isNaN does is check to see if the value passed is equal* to this special value. If you want to check if something is, say, not a stream of numbers, you can use a regular expression:
if (!/^\d+(\.\d+)?/.exec(person)) {
Or parse the value as a number and see if it converts back to the same string:
var n = parseFloat(person);
if (n.toString() !== person) {
*There's a reason that we don't use === but it's outside the scope of this answer.
The isNaN function checks if a value is NaN. NaN is a value that occurs when making operations that require numbers with non-numbers. Please see the documentation.
However the function does not check if the value is of type number. Too check if a value is of type number use the typeof operator
typeof person === 'number'
Your code is the correct way of using the isNaN method. However for anyone else reading this post I have seen a strange anomaly where the documented usage of IsNaN hasn't worked properly and I got around the problem by combining the parseInt method with the IsNaN method. According to the W3c web site (https://www.w3schools.com/jsref/jsref_isnan.asp) the IsNan('123') should return false and IsNan('g12') should return true, but I've seen scenarios where this isn't the case.
If you're having trouble getting the documented methods to work try this code below:
var unitsToAdd = parseInt($('#unitsToAdd').val());
if(isNaN(unitsToAdd)) {
alert('not a number');
$('#unitsToAdd').val('1');
returnVal = false;
}
Alternatively you can try this method which is well tested.
function isNumber(searchValue) {
var found = searchValue.search(/^(\d*\.?\d*)$/);
//Change to ^(\d*\.?\d+)$ if you don't want the number to end with a . such as 2.
//Currently validates .2, 0.2, 2.0 and 2.
if(found > -1) {
return true;
}
else {
return false;
}
}
Hope this helps.

Check for number within a url using javascript?

I've a gallery within a website and each gallery image is represented by a url like so:
http://www.example.com/gallery/my-photos#10
http://www.example.com/gallery/my-photos#11
http://www.example.com/gallery/my-photos#12
.
.
.
.
.
I've created a conditional statement to prevent user from invalid url.
var galleryNum = window.location.hash.substring(1);
if( typeof(galleryNum) == "string" || typeof(galleryNum) == "NaN" ){
console.log('this is not a number');
}else if(typeof(galleryNum) == "number"){
console.log('this is a number');
}
However this doesn't work, the value I get from window.location.hash.substring(1) will always be a string regardless I enter number or a string.
if you want to get number, you should use:
parseInt(galleryNum,10)
if you want to check whether galleryNum is number or not, you can use:
isNaN(parseInt(galleryNum,10))
Try utilizing .test()
if( /\d/.test(galleryNum) ) {
// `Number`
} else {
// not `Number`
}
there is no "NaN" type. In fact, despite NaN standing for Not-a-Number, it actually is a number: typeof NaN === 'number'
You can however use isNaN() to test for NaN.
To test if the string returned from the URL can be cast to a number, use parseInt:
var galleryNum = parseInt(window.location.hash.substring(1),10);
if (typeof(galleryNum) === 'number' && !isNan(galleryNum)) {
// got a number here
}

How to check if a string contains a given string using jQuery

I Use this Code to check a char is contain in string if true checked checkbox but it always return true.why??
//it is mvc project and after execution it become like this:if ($("123:contains(1)"))
if ($("#Model.VillageAR.IncomeLocation.ToString():contains(1)"))
{
$('#IncomeLocation1').attr('checked', true);
}
I'm guessing you're really just looking for indexOf
if ( "#Model.VillageAR.IncomeLocation.ToString()".indexOf('1') != -1 ) {
$('#IncomeLocation1').prop('checked', true);
}

Javascript RegEx.Test always returning true

I have a value in a text input I need to verify as a date in the format dd/mm/yyyy. Below is my code. I always get true regardless of what I enter in the text input. Otherwise function works well. Always displays an alert with the value I put in the text input.
function checkDate(date)
{
var result;
var expression = /[0-9]{2}\/[0-9]{2}\/[0-9]{4}/;
result = expression.test(date.value);
if(result=true)
{
alert(date.value);
}
else
{
alert("false finally");
}
}
if(result==true)
{
alert(date.value);
}
instead having single "=" have "==" , else you can use like this
if (result)
{
alert(date.value);
}
and always remember this
"1" == 1 // true
"1" === 1 // false
An example of type coercion at work. Basically anytime your value is the "same" but the type isn't then == works.
Please use === everywhere. There's no need to use ==. checking for types is always better. If something breaks then you can convert from type a to type b

Checking only the integer values through Regex

My Code:
I tried the following code
<SCRIPT type="text/javascript">
var num = "10";
var expRegex = /^\d+$/;
if(expRegex.test(num))
{
alert('Integer');
}
else
{
alert('Not an Integer');
}
</SCRIPT>
I am getting the result as Integer. Actually I declared the num varibale with double quotes. Obviously it is considered as a string. Actually I need to get the result as Not an Integer. How to change the RegEx so that I can get the expected result.
In this case, it should give the result as Not an Integer. But I am getting as Integer.
if(typeof num === "number" &&
Math.floor(num) === num)
alert('Integer');
else
alert('Not an Integer');
Regular expressions are there to work on strings. So if you tried it with something else than a string the string would either be converted or you would get an error. And yours returns true, because obviously the string only contains digit characters (and that is what you are checking for).
Use the typeof operator instead. But JavaScript doesn't have dedicated types for int and float. So you have to do the integer check yourself. If floor doesn't change the value, then you have an integer.
There is one more caveat. Infinity is a number and calling Math.floor() on it will result in Infinity again, so you get a false positive there. You can change that like this:
if(typeof num === "number" &&
isFinite(num) &&
Math.floor(num) === num)
...
Seeing your regex you might want to accept only positive integers:
if(typeof num === "number" &&
isFinite(num) &&
Math.floor(Math.abs(num)) === num)
...
RegExp is for strings. You can check for typeof num == 'number' but you will need to perform multiple checks for floats etc. You can also use a small bitwise operator to check for integers:
function isInt(num) {
num = Math.abs(num); // if you want to allow negative (thx buettner)
return num >>> 0 == num;
}
isInt(10.1) // false
isInt("10") // false
isInt(10) // true
I think it's easier to use isNaN().
if(!isNaN(num))
{
alert('Integer !');
}
else
{
alert('Not an Integer !');
}
Léon

Categories