is there a way to force focus on first invalid input, after run a validation routine? something like this:
$("input:invalid:first").focus();
or
$("input:first:invalid").focus();
With Angular Forms, we can help the user by focusing the first invalid input when they submit the form. In this example form, we have two inputs. Each input has a required validator to ensure the user has entered a value. Our form is using Angular Reactive Forms and the FormBuilder service to create the logic for our form.
When you submit a form, that has missing required input or has invalid data (e.g. malformed email), after clicking form submit user should be shown the invalid field (focus). If long form, screen stays at bottom of form and you cannot see invalid fields without having to scroll up
That’s because the code we wrote only auto-focuses the first input field once on each page load. If you do anything outside of immediately typing inside the auto-focused input field, then it won’t auto-focus again, until you do another page refresh.
The onload event executes a function that finds the input field with the firstField ID via document.getElementById and then uses the JavaScript focus () method to set the state of the input field to focus. Does the focus outline disappear from your input field all of a sudden?
You can select your input based upon a class and then use :first filter
$('.error').filter(":first").focus()
This gives a much better performance since :first is a jQuery extension and not part of the CSS specification.Queries using :first cannot take advantage of the performance boost provided by the native DOM querySelectorAll() method.
Edited: You can use jQuery plugin like jQuery Validator. Which adds a class error on invalid input, so you can capture it and change focus
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With