Click here to Skip to main content
Click here to Skip to main content

Tagged as

Allow only Numeric values in ASP Text box control using JavaScript

, 11 Feb 2012 CPOL
Rate this:
Please Sign up or sign in to vote.
Allow only Numeric (either whole or decimal) values in ASP Text box control using JavaScript
This allows only numeric (either whole or decimal) values in ASP Textbox control using JavaScript using ASP textbox key down event to fire the JavaScript function.
 

Example

<asp:TextBox ID="txtDaysOutLB" Text="" MaxLength="4" onkeydown="return jsDecimals(event);" Width="75px" runat="server"></asp:TextBox>

Javascript Function

function jsDecimals(e) {
 
    var evt = (e) ? e : window.event;
    var key = (evt.keyCode) ? evt.keyCode : evt.which;
    if (key != null) {
        key = parseInt(key, 10);
        if ((key < 48 || key > 57) && (key < 96 || key > 105)) {
            if (!jsIsUserFriendlyChar(key, "Decimals")) {
                return false;
            }
        }
        else {
            if (evt.shiftKey) {
                return false;
            }
        }
    }
    return true;
}
 
// Function to check for user friendly keys  
//------------------------------------------
function jsIsUserFriendlyChar(val, step) {
    // Backspace, Tab, Enter, Insert, and Delete  
    if (val == 8 || val == 9 || val == 13 || val == 45 || val == 46) {
        return true;
    }
    // Ctrl, Alt, CapsLock, Home, End, and Arrows  
    if ((val > 16 && val < 21) || (val > 34 && val < 41)) {
        return true;
    }
    if (step == "Decimals") {
        if (val == 190 || val == 110) {  //Check dot key code should be allowed
            return true;
        }
    }
    // The rest  
    return false;
}

License

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

Share

About the Author

Ramanujam Shankar
Web Developer Mahindra Logisoft Business Solution Limited, Chenn
India India
No Biography provided

Comments and Discussions

 
QuestionAllow only numeric values in ASP Text box control with javascript PinmemberMember 112042923-Nov-14 19:58 
QuestionIT solved my problem thanks!!! PinmemberMember 365210621-Nov-13 4:32 
QuestionVery helpful but... Pinmemberdstamm5-Oct-13 9:05 
GeneralMy vote of 4 Pinmembercoolnavjot313-Jun-13 0:11 
GeneralMy vote of 5 PinmemberNastaranZ19-Apr-13 0:04 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.141223.1 | Last Updated 11 Feb 2012
Article Copyright 2012 by Ramanujam Shankar
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid