0

I am new for JavaScript can you please suggest me how to validate float value on key press event. I have tried a example it is taking two '.'

Pranay Rana
  • 175,020
  • 35
  • 237
  • 263

1 Answers1

1

here is the code for you , this function can be used for integer as well as decimal

<input id="MyTextBox1" onkeypress=' IntegerAndDecimal(event,this,true)' >


function IntegerAndDecimal(e,obj,isDecimal)
{
    if ([e.keyCode||e.which]==8) //this is to allow backspace
    return true;

    if ([e.keyCode||e.which]==46) //this is to allow decimal point
    {
      if(isDecimal=='true')
      {
        var val = obj.value;
        if(val.indexOf(".") > -1)
        {
            e.returnValue = false;
            return false;
        }
        return true;
      }
      else
      {
        e.returnValue = false;
        return false;
      }
    }

    if ([e.keyCode||e.which] < 48 || [e.keyCode||e.which] > 57)
    e.preventDefault? e.preventDefault() : e.returnValue = false; 
}
Pranay Rana
  • 175,020
  • 35
  • 237
  • 263