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');
ES6 Update
Here's the ES6 version of the script using arrow function and template literals:
document.querySelectorAll(':input:visible').forEach(input => {
input.setAttribute('tabindex', '0');
});
or we can use a single-line arrow function to set the tabindex attribute for each input element:
document.querySelectorAll(':input:visible').forEach(input => input.setAttribute('tabindex', '0'));