Click here to Skip to main content
15,884,353 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hello all.
I have two questions:

1)I have a textbox in asp.net web form. I want to restrict users to enter only decimals in this textbox.
I know the JQuery code for this purpose,but how can I do this using javascipt?
This is what I did:
JavaScript
function isNumberKey_decimal(evt) {
       var charCode = (evt.which) ? evt.which : evt.keyCode;
       if (charCode != 46 && charCode > 31
         && (charCode < 48 || charCode > 57))
           return false;
       return true;
   }

C#
protected void Page_Load(object sender, EventArgs e)
    {
        txt1.Attributes.Add("onkeypress", "return isNumberKey_decimal(event)");
    }

It works,but there is a problem. It doesn't prevent from entering different dots. For example, 10..2 or 10.. , are allowed. How can I prevent from this?

2)I have another textbox. I want to force users to enter only numbers 1 to 10. How can I do this using java script?

Please help me.
Thanks a lot.


Update:

Finally I could find the answer of my first question:
JavaScript
function isNumberKey_decimal(evt) {
    
    var charCode = (evt.which) ? evt.which : event.keyCode;
    if (charCode == 46 && evt.srcElement.value.split('.').length > 1) {
        return false;
    }
    if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57))
        return false;
    return true;
}

Hope it helps you.

Can anyone answer my second question please?
Thanks a million.
Posted
Updated 23-Nov-14 22:31pm
v2

1 solution

A simple Google suffices: Validating floating point numbers in javascript[^]
I'd look at the regular expression solutions there.
 
Share this answer
 
Comments
k5_ce 24-Nov-14 4:26am    
Thanks a lot for your answer.
I have read different solutions in this link. Although they were fine, I couldn't find the right answer for decimal numbers. I wanted to fore users to enter just positive numbers with a single dot. Finally, I could find the solution in a link. I put it for all of you. Hope it helps.
I couldn't find the answer of my second question. Can anyone helps me?
Thanks a lot

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