Home > OS >  Trying to navigate a form with the enter key - freezes on 'display:none' inputs
Trying to navigate a form with the enter key - freezes on 'display:none' inputs

Time:07-06

I am using the following jQuery to allow a user to navigate a form with the enter key. It works, however, some of the inputs I created get turned off using display:none based on the user’s responses.

When the user approaches one of these off inputs, it freezes. It will not continue to the next input. I can’t hide the input using visibility:hidden or opacity:0 instead because neither option will work for this specific purpose.

Is there a line of code I can add to the jQuery that says “skip input if display = none”? Or is there an easier method altogether?

$(document).ready(function() {
    var allInputs = $(':text:visible');
    $(":text").on("keyup", function() {
        if (event.key !== "Enter") return;
        event.preventDefault(); {
            var nextInput = allInputs.get(allInputs.index(this)   1);
            if (nextInput) {
                nextInput.focus();
            }
        }
    });
});
.input:not(:focus):not(:placeholder-shown):valid ~ .remove {
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input  pattern="(1)" placeholder=" ">
<input>
<input>
<input >

<br>

<input>
<input>
<input>
<input>

CodePudding user response:

Because inputs get shown/hidden after page load (document ready) you should re-query the visible inputs.

This is how I changed your code in the ready event handler: I moved allInputs initialization inside of the keyup so it is calculated every time. This is because inputs can be shown and hidden dynamically.

$(document).ready(function() {
    $(":text").on("keyup", function() {
        var allInputs = $('input:visible');
        if (event.key !== "Enter") return;
        event.preventDefault(); {
            var nextInput = allInputs.get(allInputs.index(this)   1);
            if (nextInput) {
                nextInput.focus();
            }
        }
    });
});

CodePudding user response:

Since the input is no longer needed, disable it and it will work properly.

$(document).ready(function() {
    var allInputs = $(':text:visible');
    $(":text").on("keyup", function() {
        if (event.key !== "Enter") return;
        event.preventDefault(); {
            var nextInput = allInputs.get(allInputs.index(this)   1);
            if (nextInput) {
                nextInput.focus();
            }
        }
    });
});
.input:not(:focus):not(:placeholder-shown):valid ~ .remove {
  display: none; disabled
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input  pattern="(1)" placeholder=" ">
<input>
<input>
<input >

<br>

<input>
<input>
<input>
<input>

  • Related