Javascript – Need to insert a ‘dot’ in textbox where the textbox is validated by using javascript to enter only numerical values

asciijavascript

Here is the code which woks perfectly and validate to enter only digits in a TEXT BOX. Now i have a problem there. My problem is i need to enter decimal values there. So i need to enter 'DOT' in the TEXT BOX. This validation has been done by using ASCII values. I even use the ASCII value of 'DOT -> 249, 250'. But it doesn't work. Any help will be appreciated.

function enterNumerics(e)
{           
    if (!e) var e = window.event;

    if(!e.which) key = e.keyCode; 

    else key = e.which; 

    if((key>=48)&&(key<=57)||key==8||key==9||key==32||key==45 || key==43)
    {
            key=key; 
            document.getElementById('bal').innerHTML ='';
            return true;
    }
    else
    {
       document.getElementById('bal').innerHTML =
            "&nbsp;&nbsp;Please Enter Numerical Values ";
       return false;
    }
}

Thanks in Advance…..

Best Answer

You can use regular expressions instead:

function validate(){
    var val=document.getElementById("field").value; //Field value 
    if(/^[0-9\.]+$/.test(val)){    
      document.getElementById('bal').innerHTML='';    
      return true; 
    }else{    
      document.getElementById('bal').innerHTML="  Please Enter Numerical Values ";    
      return false; 
    }
}

then you call the validate function with onKeyPress event