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++); });
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.
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.
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.
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.
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.
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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With