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....

Recommended Answers

All 3 Replies

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

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>
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.