How can I focus the first invalid input when a modal form is submitted?
Asked on Jun 28, 2025
1 Answer
To focus the first invalid input in a modal form when it is submitted, you can use JavaScript to detect invalid fields and set focus on the first one. Here's a simple example using Bootstrap 5.
<!-- BEGIN COPY / PASTE -->
<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Form Modal</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<form id="myForm" novalidate>
<div class="mb-3">
<label for="email" class="form-label">Email address</label>
<input type="email" class="form-control" id="email" required>
<div class="invalid-feedback">
Please enter a valid email.
</div>
</div>
<div class="mb-3">
<label for="password" class="form-label">Password</label>
<input type="password" class="form-control" id="password" required>
<div class="invalid-feedback">
Please provide a password.
</div>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</div>
</div>
</div>
<script>
document.getElementById('myForm').addEventListener('submit', function(event) {
event.preventDefault();
event.stopPropagation();
if (!this.checkValidity()) {
this.classList.add('was-validated');
const firstInvalid = this.querySelector(':invalid');
if (firstInvalid) {
firstInvalid.focus();
}
}
});
</script>
<!-- END COPY / PASTE -->
Additional Comment:
✅ Answered with Bootstrap 5 best practices.- Ensure the form has the `novalidate` attribute to prevent the browser's default validation.
- The script listens for the form's `submit` event, prevents the default submission, and checks validity.
- If the form is invalid, it adds the `was-validated` class and focuses the first invalid input.
- The `:invalid` CSS pseudo-class is used to find the first invalid input.