Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding tabindex dynamically

I'd like to add tabindex to all form elements. The form is dynamic and I can't add it to the HTML. I would like to run it as a function.

If there are several radio buttons with the same name, each must have it's own tabindex value. Most of the form elements on page start as <input>, except <select>. How do I account for that?

I guess I will need to run a loop and add the attribute, right?

var n = 1;   $('input, select').each(function() {                    $(this).attr('tabindex', n++); }); 
like image 711
santa Avatar asked Feb 27 '13 21:02

santa


People also ask

How do you set a dynamic tab index?

By setting tabindex="-1" on an element it gets removed from the list of focusable items on the page and effectively hidden from a screen reader. tabindex="-1" should only ever be used on items that are not focusable in the first place to allow them to receive focus programatically.

How add Tabindex attribute in jQuery?

let n = 1; $(':input:visible'). attr('tabindex', () => n++); Using () => n++ instead of just n++ here allows jQuery to run the function for each instance's value rather than taking in the initial value of n++ and applying it to all matching elements.

Can we add Tabindex in CSS?

non-standards-compliant: set the tabindex attribute on a DIV . This will work in all common browsers. standards-compliant: replace DIV by an anchor element ( A ) without a href attribute set, style it with display: block and add the tabindex attribute.

What does Tabindex =- 1 mean?

A negative value (usually tabindex="-1" ) means that the element is not reachable via sequential keyboard navigation, but could be focused with JavaScript or visually by clicking with the mouse. It's mostly useful to create accessible widgets with JavaScript.


2 Answers

Strange question, but yes that's the basic idea:

$(":input:not(:hidden)").each(function (i) { $(this).attr('tabindex', i + 1); }); 

This uses :input to get everything including buttons and text areas. :not(:hidden) will just exclude the hidden inputs to avoid unnecessary tabs.

like image 52
Brandon Avatar answered Sep 20 '22 20:09

Brandon


Might be better to avoid n++ to set different tabindex numbers.

Instead, try setting tabindex to 0:

$(':input:visible').each(function() {                    $(this).attr('tabindex', '0'); }); 

tabindex="0" means that the element should be focusable in sequential keyboard navigation, but its order is defined by the document's source order. ~ developer.mozilla.org

The :input selector basically selects all form controls.

The :visible selector basically selects all elements that are visible.


or as suggested in the comments, if you have no other changes to apply to each visible input, then this should be enough:

$(':input:visible').attr('tabindex', '0'); 
like image 39
allenski Avatar answered Sep 19 '22 20:09

allenski