Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Trying to navigate a form with the enter key – freezes on 'display:none' inputs

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

$(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 class="input" pattern="(1)" placeholder=" ">
<input>
<input>
<input class="remove">

<br>

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

>Solution :

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();
            }
        }
    });
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading