65.9K
CodeProject is changing. Read more.
Home

KeyPress event: restrict value for repeating character

starIconstarIconstarIconstarIconemptyStarIcon

4.00/5 (1 vote)

Sep 4, 2011

CPOL
viewsIcon

12691

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;
    }
}