DaniWeb IT Discussion Community

DaniWeb IT Discussion Community (http://www.daniweb.com/forums/index.php)
-   HTML and CSS (http://www.daniweb.com/forums/forum143.html)
-   -   finding out variable type from html input type tag in javascsript (http://www.daniweb.com/forums/thread54133.html)

amaravanich Sep 4th, 2006 4:21 am
finding out variable type from html input type tag in javascsript
 
Hi,
I'm trying to get the data type of a value entered into an input type text field in a form.By using typeof i am getting string always.Eventhough i was entered a number i'm getting the type of data as string.How can i check whether it is a number or not? throw java script???????please reply me.
thanks in advance....

hollystyles Sep 4th, 2006 5:26 am
Re: finding out variable type from html input type tag in javascsript
 
Javascript by it's nature treats everything as a string, certainly all HTML controls that suport a value it will always be a string. Well more accurately everything is an object, and whenever you read that object in your code it tends to be implicitly converted or cast as a string. You have to explicitly cast your varables to a number when you require that behaviour, using the Number(string value) function e.g.

    var myNumber; 

    myNumber =  Number(document.getElementById("myTextBox").value);
   
    if(myNumber == NaN)
        alert("You must enter a number");


you can also consider parseFloat() and parseInt()
http://www.javascripter.net/faq/convert2.htm

Another usefull link:
http://www.w3schools.com/jsref/jsref_Number.asp

amaravanich Sep 4th, 2006 6:08 am
Re: finding out variable type from html input type tag in javascsript
 
Thanku very much for ur reply.I'm trying like this but no result its resulted true for every input.can u please tell me wts wrong with this?
if(f.age.value!=""&&f.id.value!=""&&f.name.value!="")
{
var myNumber;
myNumber = Number(f.age.value);
if(myNumber == NaN)
{
alert("You must enter a number");
return false;
}else{return true;}

}

else{
if(f.age.value=="")
{
alert("you have to fill your age");
return false;
}
if(f.id.value=="")
{alert("you have to fill your id");
return false;
}

if(f.name.value=="");
{
alert("you have to enter name");
return false;
}

}
}
</script>

hollystyles Sep 4th, 2006 6:29 am
Re: finding out variable type from html input type tag in javascsript
 
Sorry my mistake try this instead:

if(isNaN(myNumber))
    return false;
else
    return true;

see here:
http://www.w3schools.com/jsref/jsref_Number.asp


All times are GMT -4. The time now is 4:25 pm.

Forum system based on vBulletin Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
©2003 - 2009 DaniWeb® LLC