Sunday, April 18, 2010

Enable only Numbers & Dot using Javascript

function inputOnlyNumbers(evt){ 
    var e = window.event || evt; // for trans-browser compatibility 
    var charCode = e.which || e.keyCode; 
    if ((charCode > 45 && charCode < 58) || charCode == 8){ 
        return true; 
    } 
    return false; 
}

The Code to be used in HTML page to enable only numbers & dots as shown below.

<input name="weight" size="15" id="weight" tabindex="9" type="text" maxlength="5" onkeypress="return inputOnlyNumbers(event)"/>

If we want to enable only numbers without the dot.....
just change the if condition in Javascript as shown below.

if ((charCode > 47 && charCode < 58) || charCode == 8)

8 comments:

professional killer said...

tyhank u sooooooo much

½ Informatics 1/2 Architecture said...

thanks man!you're a life saver!

lnkhatri said...

it's allowing division sign....
please help

Anil Kumar said...

Just change the if Condition in the function as below

if ((charCode > 47 && charCode < 58) || charCode == 8 || charCode == 45 || charCode == 46)

It works

dsp said...

Thank You Good Work

Unknown said...

You've really made my day great. However i need help, how do i get 2 digit value after the dot

Anil Kumar said...

Its used for not allowing the dot and number, if u require to allow 2 characters of the dot...plz use the below code so that it accepts 2 characters after dot

var str = document.getElementById("example").value();
var new_arr = str.split(".");
if(new_arr[1] != undefined)
{
if(new_arr[1].length > 2)
{
throw an error
}

}

Hope it helps u, or else u can use regular expressions

Unknown said...

thank you, but i want to ask if you can give me the full code on how to do it.