how to fire an event when the TAB key is pressed?

2019-09-07 06:17发布

问题:

I just want to "catch" when some user press the TAB key in a Textbox. I'm working in a simple CRUD asp.net application, c# as code behind.

I try to do this as a test:

private void KeyForm_KeyDown( object sender, KeyEventArgs e )
      {
         keyInfoLabel.Text =
            "KeyCode: " + e.KeyCode + '\n' +
            "KeyData: " + e.KeyData + '\n' +
            "KeyValue: " + e.KeyValue;
      } 

But it just works with C# desktop application.

回答1:

TAB key can not be catched by KeyPress or KeyDown. so to achieve your requirement use Leave Event for TextBox.

In Leave Event definition move the focus back to TextBox...

like this...

private void textBox1_Leave(object sender, EventArgs e) {
textBox1.Text="Khan Pressed the TAB"; textBox1.Focus(); }



回答2:

$('#textbox').live('keydown', function(e) { 
  var keyCode = e.keyCode || e.which; 

  if (keyCode == 9) { 
    e.preventDefault(); 
    // call custom function here
  } 
});

use java script



回答3:

$(document).ready(function () {
    $('#<%= testTextBox.ClientID%>').keydown(function (e) {
       var code = (e.keyCode ? e.keyCode : e.which);
           if (code == 9) {
             $('#<%= 2ndTextBox.ClientID%>').focus()
                return false;
             }
    });
});

It can be useful for somebody.

regards