Reputation: 10271
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 functionality). 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.
Upvotes: 2
Views: 4815
Reputation: 19560
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();
}
});
Upvotes: 0
Reputation: 7297
Sounds like you want to have the tab wrap on the first and last element.
$('#form').find('input, textarea, select').first();
$('#form').find('input, textarea, select').first();
.keydown()
.focus()
edit: selector logic was wrong
e.g.: http://jsfiddle.net/rkw79/fuXyf/
Upvotes: 0
Reputation: 23142
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
}
});
Upvotes: 2
Reputation: 17960
You could use the first and last child selectors:
var first = $("#form-name:first-child");
var last = $("#form-name:last-child");
Upvotes: 0