2

onkeypress is not working with textbox in asp.net webform I want to prevent special characters and alphabets

Following is the aspx

<wijmo:C1InputText ID="SAC" runat="server" Style="width: 150px; display: inline-block;" onkeydown="return onlyNumbers(this,event);">
</wijmo:C1InputText>

function onlyNumbers(txt, event) {
    var charCode = (event.which) ? event.which : event.keyCode
    if (charCode == 46) {
        if (txt.value.indexOf(".") < 0)
            return true;
        else
            return false;
    }
       var regex = new RegExp("^[a-zA-Z0-9]+$");
    var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
    if (!regex.test(key)) {
       event.preventDefault();
       return false;
    }        
    if (charCode > 31 && (charCode < 48 || charCode > 57) && charCode!=190)
        return false;
    return true;
}

It returns false but not preventing to enter. If I replaced onkeypress with onkeydown it works

RackM
  • 449
  • 7
  • 26
  • `onkeypress` sets `event.charCode` instead of `event.keyCode`. However it's being deprecated and you should use `onkeydown` instead. I'm not sure what you're asking exactly, your question sounds like everything works fine if you use `onkeydown` instead, so what's the issue exactly? –  Jul 30 '19 at 08:37
  • edited the questions. Actually I am trying to prevent special character and alphabets. Only numeric and decimals allowed. And using onkeydown it is not working as well as with on keypress – RackM Jul 30 '19 at 09:23
  • `using onkeydown it is not working as well as with on keypress` how exactly? Can you elaborate? Again: `onkeypress` is being deprecated right now. –  Jul 30 '19 at 09:35

1 Answers1

0

Please have a look on this post :

https://forums.asp.net/t/1888076.aspx?onKeyPress+vs+OnKeyDown+vs+OnKeyUp

this is the part of the answer you want :

OnKeyDown allows you to fire an event prior to the character being entered within the Textbox, so that you could check what the character being pressed is prior to determining if it should be allowed or not.

OnKeyUp will allow you to essentially hold a key down and will not fire an event until the key is released.

OnKeyPress will fire an event for each character key that is pressed (including those being held down).

Community
  • 1
  • 1
taktak
  • 90
  • 10
  • yeah but how to prevent from entering with onkeypress event – RackM Jul 30 '19 at 08:21
  • As I said, the KeyPressed event fire only with characters ([a-z][0-9]). Here, you try to catch the "." so you can only catch it with onkeydown. Please look this post : https://stackoverflow.com/questions/1367700/whats-the-difference-between-keydown-and-keypress-in-net don't forget to mark this answer as a solution if it helped you to find out what was wrong. – taktak Jul 30 '19 at 08:24