JQuery UI using: tabbable to find the next and previous tabbable element

I am trying to use jQuery UI :tabbable to select the next and previous input elements on a page. I have the following html

 <div id="section1">1. <input type="text" />2. <input type="text" /> </div> <div id="section2">3. <input type="text" />4. <input type="text" />5. <input type="text" /> </div> 

and next javascript

 $(document).ready(function () { $("input").on("keyup", function (event) { if (event.keyCode == 40) $(this).next(":tabbable").focus(); else if (event.keyCode == 38) $(this).prev(":tabbable").focus(); }); }); 

The selector seems to work fine in a div. For example, if I am at input 3 and press down, it will go to input 4. However, if I press, the selector cannot find input 2. I cannot figure out how to find the previous tabbable on the page.

Jsfiddle example

+4
source share
2 answers

You can use .index() input elements as a way to switch between them.

 $("input").on("keyup", function (event) { if (event.keyCode == 40) { $('input').eq(parseInt($('input').index($(this)), 10) + 1).focus(); } else if (event.keyCode == 38) { $('input').eq(parseInt($('input').index($(this)), 10) - 1).focus(); } }); 

JsFiddle example

+4
source

Will this work for you:

 $(document).ready(function () { $("input").on("keyup", function (event) { if (event.keyCode == 40) { $nextTabbable = $(this).next(":tabbable").length ? $(this).next(":tabbable") : $(this).parent().next().find(":tabbable").first() ; $nextTabbable.focus(); } else if (event.keyCode == 38) { $prevTabbable = $(this).prev(":tabbable").length ? $(this).prev(":tabbable") : $(this).parent().prev().find(":tabbable").last() ; $prevTabbable.focus(); } }); }); 

Here is jsfiddle

0
source

All Articles