3

For example, if I have the following code:

<form id="one">
    <input type="text"/>
</form>

<form id="two">
    <input type="text"/>
</form>

When I select the input in form "one", the Next button appears, and when I click Next, it takes me to the input in form "two".

Is there a way to only have Next and Previous for form elements inside the current form?

supercoolville
  • 8,636
  • 20
  • 52
  • 69

1 Answers1

6

You can accomplish this with negative tab indexes on each input.

<form id="one">
    <input type="text" tabindex="-1">
</form>

<form id="two">
    <input type="text" tabindex="-2">
</form>

The above example will prevent tabbing from the form with an ID of "one" to the form with an ID of "two." That said, it doesn't addresses the question of being able to tab inside the active form.

For that you could start with positive tab indexes for the inputs in the first form and negative tab indexes on the inputs in the second form. When an input in the second form is focused, you would update the tab indexes for the first form to be negative. It's a convoluted approach, but it will work.

Update

Here is a Fiddle of how the above solution might work. The JavaScript code could be optimized more, but it should clarify my answer to this question. Please try it out and let me know how it goes.

Here is the HTML:

<form id="a">
    <input type="text">
    <input type="text">
</form>

<form id="b">
    <input type="text">
    <input type="text">
</form>

<form id="c">
    <input type="text">
    <input type="text">
</form>

Here is the JavaScript:

// jQuery
var $allInputs = $("input"),
    numInputs = $allInputs.length;

// Update the tab indexes when an input is focused.
$("form").on("focus", "input", function() {
    var $activeForm = $(this).closest("form"),
        $activeFormInputs = $activeForm.find("input");

    // Make the inputs on all inactive forms negative.
    $.each($allInputs, function(i) {
        var $parentForm = $(this).closest("form");

        if ($parentForm != $activeForm) {
            $(this).attr("tabindex", -(numInputs - i));
            $(this).val(-(numInputs - i));
        }
    });

    // This form is active; use positive tab indexes.
    $.each($activeFormInputs, function(i) {
        $(this).attr("tabindex", ++i);
        $(this).val(i)
    });   
});

// Focus the first input.
$("#a").find("input").first().focus();
JWK
  • 3,345
  • 2
  • 19
  • 27
  • Thanks!!!!!!!!!! Your solution gave me a better idea. On focus(), I used hide() to hide the second form. Then Next and Previous were disabled!!! :D – supercoolville Sep 05 '13 at 05:17
  • If both tabindex are -1, then it still shows prev and next, maybe ios will ignore tabindex when they have the same value. – jiguang Jun 01 '15 at 02:58