Click here to Skip to main content
16,019,764 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How to write script which respond on each key pressed for text box and prevent from displaying a particular key in Textbox in ASP.NET
Posted

You can handle the KeyPress[^] event in JavaScript.
 
Share this answer
 
You need to use JavaScript to handle this. I would typically look at using jQuery to make this functionality a lot easier, then you would hook up like this:
JavaScript
$(document).ready(function() {
  $('#allTextBoxesToWatch').keypress(function(ev) { 
    if (ev.which == 13)
      ev.preventDefault();
  });
});
In this example (which I've just typed from memory, so I apologise if it isn't 100% exact), it binds all textboxes that have a class of allTextBoxesToWatch to the keypress event. It then determines whether or not the user pressed the key with an ascii value of 13, and prevents the default action if it does.
 
Share this answer
 
Comments
Vijay Vishwakarmar 14-Jul-11 9:25am    
Thanks for the reply but you please describe it in detail.
Pete O'Hanlon 14-Jul-11 9:38am    
I've just given you the code for it. How much more detail do you expect?
Vijay Vishwakarmar 14-Jul-11 9:45am    
Complete example with one textbox having keypress event and suspending a particular key
[no name] 14-Jul-11 9:49am    
The examples should be more than enough for anyone to come up with their own code. There's no spoon-feeding here.
Pete O'Hanlon 14-Jul-11 10:37am    
Well said.
For example, this is how to filter all characters but digits:

HTML
<html>
   <head>
      <script type="text/javascript"><!--
         function filterDigits(eventInstance) { 
            eventInstance = eventInstance || window.event;
                key = eventInstance.keyCode || eventInstance.which;
            if ((47 < key) && (key < 58) || key = 45 || key == 8) {
               return true;
            } else {
               if (eventInstance.preventDefault)
                  eventInstance.preventDefault();
               eventInstance.returnValue = false;
               return false;
            } //if
         } //filterDigits
      --></script>
   </head>
<body">

<input type="text" onkeypress="filterDigits(event)"/>

</body>
</html>


Pay attention that you also have to allow #8 (backspace).

—SA
 
Share this answer
 

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900