开发者

Detect when user presses tab on first or last form element (in div)

I have an HTML form spread across several divs. I need to know when the user presses the tab key when they are on the first or last element within each div (so I can apply some custom tab functionalit开发者_运维技巧y). For the first element in the div I'm looking for Tab+Shift; for the last element I'm looking for Tab only. The elements could be textboxes, textareas, radio buttons, select lists, or check boxes.

What is the most efficient way to detect the first and last elements? Happy to use a jQuery solution.

Thanks.


You can use the :first-child and :last-child selectors to find the form elements. Then, you can attach a keydown event handler and check for SHIFT+TAB and TAB respectively.

$('div input:first-child').keydown(function(event) {
    if (event.which == 9 && event.shiftKey) { // Tab is keycode 9
        // Do custom tab handling
    }
});

$('div input:last-child').keydown(function(event) {
    if (event.which == 9) {
        // Do custom tab handling
    }
});


As long as the inputs truly the first and last children of the DIVs, the below will work. Otherwise you will need to get a little more tricky with the selection.

Edit: My assertion about child order seems to be incorrect. This should work for most situations. End Edit

If you want it to be specific to certain kinds of input, or anything which is considered input but isn't actually an input element, the selector will need some minor adjustment.

Demo

http://jsfiddle.net/JAAulde/tHkdz/

Code

$('#myform')
  .find('div input:first-child, div input:last-child')
  .bind('keydown', function(e) {
    if (e.which === 9) {
      // custom code here
      e.preventDefault();
    }
  });


You could use the first and last child selectors:

var first = $("#form-name:first-child");
var last = $("#form-name:last-child");


Sounds like you want to have the tab wrap on the first and last element.

  • Get the first: $('#form').find('input, textarea, select').first();
  • Get the last: $('#form').find('input, textarea, select').first();
  • Bind keydown to the elements: .keydown()
    • use this to determine which key was pressed: jQuery Event Keypress: Which key was pressed?
    • Then focus on the element you want: .focus()

edit: selector logic was wrong

e.g.: http://jsfiddle.net/rkw79/fuXyf/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜