Javascript – Change tabindex dynamically in jquery

asp.netjavascriptjquery

Imagine this simple layout ( http://jsfiddle.net/4F9cL/ ).
We have a table, for each row i have a label a textbox and a checkbox.
The first textbox has tabindex = 1 , the first checkbox has tabindex = 2, the next textbox on the second row has tabindex = 3 and so on.

What i would like to do is change the tabindex on the checkbox on the same row for the textbox that im in if the content of the textbox has changed.

For example at the moment im checking the checkbox on the row that the thebox content has been changed, i do that with the following code:

 $("input:text").change(function () {
            $(this).parents('tr:first').find('input:checkbox').prop('checked', 'checked');

So the scenario is the following: If the content of the textbox hasnt changed, when i tab i want the focus to change to the checkbox on the same row. If the content of the textbox HAS changed, i would like the focus to be on the next textbox on the row below INSTEAD of the checkbox on the same row.

I hope i explained it good enough for you to understand what im trying to do.
I've tried using .removeprop() and .removeattr() but that doesnt work and when next tab hits it just goes to the bottom of the page.

Best Answer

$("input:text").change(...);

The change event of a textbox will only be executed once the textbox loses focus. This means that when you press Tab, that function has not yet run, and you'll end up with your old tabindex target.

$("input:text").keyup(...);
$("input:text").keydown(...);

These events will fire when you either press down on (keydown), or release (keyup) a button while the textbox is focused.

Something like this should do the trick:

$("input:text").keyup(function() {
    var textBox = $(this);
    var textBoxIsEmpty = textBox.val().length == 0; //I assume you use this to determine which element should be the next to get focused when pressing tab.

    var currentTabIndex = parseInt( textBox.attr("tabindex") );

    var nextTarget = GetNextTarget(textBoxIsEmpty); //not sure how you define this. This is the item you want to be your next target when you press tab.
    var nextTabIndex = currentTabIndex + 1;

    nextTarget.attr("tabindex", nextTabIndex);
});

Although I am not 100% sure if changing the tabindex dynamically works in every browser.