Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can force focus on first invalid input?

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();
like image 300
A.Pourhadi Avatar asked Jan 02 '14 08:01

A.Pourhadi


People also ask

How to help the user by focusing the first invalid input?

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.

How to view invalid fields when submitting a 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

Why won’t my input field auto-focus?

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.

How do you focus an input field in JavaScript?

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?


1 Answers

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

like image 89
Saravana Kumar Avatar answered Sep 19 '22 13:09

Saravana Kumar