Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

278
Views
How to set focus on first form element in any bootstrap modal

I have a select dropdown list and 2 input fields. I know how to set focus on first input field for ANY modal using :

$('.modal').on('shown.bs.modal', function () {
  $(this).find('input:text:visible:first').focus();
})

https://www.w3schools.com/code/tryit.asp?filename=FDG195P90CWU

But I can't see how to do when there are both dropdown lists and input fields.

about 4 years ago · Santiago Trujillo
2 answers
Answer question

0

I think you might be looking for something like this: $("select:first").focus();

Here is the JQuery code:

$(document).ready(function(){
    $("#myBtn").click(function(){
        $("#myModal").modal();
    });

  $('.modal').on('shown.bs.modal', function () {
    //$(this).find('input:text:visible:first').focus();
    $("select:first").focus();
  })

});

When you run it you can see the select box is highlighted blue (at least in Chrome it is) I found this answer based on a similar question. Hope that helps

EDIT:

If you want it to select either the first text or select field you can use:

$(this).find('input[type=text],textarea,select').filter(':visible:first').focus();

If you need it to look for additional input fields (like password or radio button) you will need to add them in the find list. Another similar question asked here.

about 4 years ago · Santiago Trujillo Report

0

Here's my solution developed on top of that by @craztmatt and others. I have extended to have the selection of the target element start at the modal that triggered the event.

// do this to make bootstrap modals auto-focus.
// delegate to body so that we only have to set it up once.
$('body').on('shown.bs.modal', function (e) {
    var ele = $(e.target).find('input[type=text],textarea,select').filter(':visible:first'); // find the first input on the bs modal
    if (ele) {ele.focus();} // if we found one then set focus.
})
about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!