Click here to Skip to main content
15,903,385 members
Articles / Programming Languages / Javascript
Tip/Trick

KeyPress event: restrict value for repeating character

Rate me:
Please Sign up or sign in to vote.
4.00/5 (1 vote)
4 Sep 2011CPOL 12.6K   1  
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)


Written By
Software Developer
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --