Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / Javascript

KeyPress event: restrict value for repeating character

4.00/5 (1 vote)
4 Sep 2011CPOL 12.7K  
Restrict value for repeating character on keypress event
Sometimes, we need to check which key was pressed or if this key is already pressed before.

This means we have to restrict repeating character.
For example: we want to enter price value in text box.
like 145.26 is valid but 145.26.35 is not
so restrict '.' for single entry

<asp:TextBox ID="Price" runat="server" Text="" onkeypress="javascript:return KeyPriceOnly(event,this);">

function KeyPriceOnly(e, object) {
    var KeyID = (window.event) ? event.keyCode : e.which;

    if ((KeyID >= 65 && KeyID <= 90) || (KeyID >= 97 && KeyID <= 122) || (KeyID >= 33 && KeyID <= 47 && KeyID != 46) ||
        (KeyID >= 58 && KeyID <= 64) || (KeyID >= 91 && KeyID <= 96) || (KeyID >= 123 && KeyID <= 126)) {
        return false;
    }

    if (KeyID == 32) {
        return false;
    }
    if ((KeyID == 46)) {
        var strvalue = object.value;
        if (strvalue.indexOf(".") > 0)
            return false;
    }
}

License

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