Click here to Skip to main content
15,914,488 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to textbox which is accepts only numbers and decimal points. so i give the following function in javascript

C#
function isn(evt)
{
var charCode = (evt.which) ? evt.which : event.keyCode
          if (charCode != 46 && charCode > 31
            && (charCode < 48 || charCode > 57))
             return false;

          return true;

}


It is working. But the textbox is accepts one more decimal points. I want textbox accepts decimal point only one time.

How to do this?

Please help me
Posted

you should check if key is decimal
then

if index of decimal in textbox value is > 0 then
return false
other wise
return true
 
Share this answer
 
use this js it will work

C#
function isn(evt)
{
var charCode = (evt.which) ? evt.which : event.keyCode
var str=evt.value;
if ((str.indexOf('.')>=0) && (event.keyCode==46)) return false;

          if (charCode != 46 && charCode > 31
            && (charCode < 48 || charCode > 57))
             return false;

          return true;

}


in your js i have added only this two line
C#
var str=evt.value;
if ((str.indexOf'.')>=0) && (event.keyCode==46)) return false;
 
Share this answer
 
Comments
devausha 23-May-12 8:21am    
Thank you for your reply. But the same problem. The decimal point is accepts more than one time.
What you need to do is to check the whole contents of the textbox and scan for the decimal. if decimal is found then return false for it. also make sure it is done in onkeypress event and not any other event.

here is some sample code. populate the value variable with your controls value and you are good to go.


JavaScript
//Get the text of text box in a variable called value here
            for(var s=0; s<value.length; ++s)
            {
                if(value.charCodeAt(s) == '.'.charCodeAt(0))
                {
                   return false;
                }
            }
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900