views:

49

answers:

3

Hello,

I have a TextBox & I want to accept just numbers in this TextBox when typing.

Thanks.

+1  A: 

A great way to accomplish this is to use the MaskedEditExtender in the Ajax control toolkit.

The example page even has a demo for limiting user input to just numbers and number-related characters.

womp
+1  A: 

I use the following client side code to do this:

jQuery.fn.ForceNumericOnly =
function()
{
    return this.each(function()
    {
        $(this).keydown(function(e)
        {
            var key = e.charCode || e.keyCode || 0;
            // allow backspace, tab, delete, arrows, numbers and keypad numbers ONLY
            return (
                key == 8 || 
                key == 9 ||
                key == 46 ||
                (key >= 37 && key <= 40) ||
                (key >= 48 && key <= 57) ||
                (key >= 96 && key <= 105));
        })
    })
};

Then in my aspx page I attach it to my TextBox with:

$(document).ready(function()
{
    $("#<%= txtMyTextBox.ClientID %>").ForceNumericOnly();
});

This is a client side ONLY check so make sure to implement a server side check using like Int32.TryParse on your data as well to ensure that there is a number.

Kelsey
@Kesley : how can I implement that ?
dotNET
@AZIRAR assuming you are using jQuery, you can just add the above javascript code, using `<script>` tags, to your aspx page that you want to implement this on. Then replace the `txtMyTextBox` with the name of your server side textbox control.
Kelsey
A: 

If you are using the AjaxControlToolkit then consider the FilteredTextBox extender.

<ajaxToolkit:FilteredTextBoxExtender ID="ftbe" runat="server" TargetControlID="YourTextBoxID" FilterType="Numbers" FilterMode="ValidChars" />
ginozola