jQuery Dynamically focus on the first INPUT or Textarea

Viewed 54082

Here's a tricky one to start the morning.

I have a series of icons. When you click an icon it loads a form. Some of the forms have input[text] others have textareas.

What I'm trying to come up with is jQuery that once I load the form I can run that will... Focus in on the first input or textarea whatever it may be, dynamically so I don't need if blocks.

Ideas?

10 Answers

Here's A solution for bootstrap modals 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. This one catches inputs, textarea AND select elements.

// 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.
})

Not precisely the OP's question but should be adaptable to a pure jquery case too.

Found this question when looking for a quick solution to select the first input with a blank value.

Came up with the following, hope it helps someone

$(':input[value=""]:enabled:visible:first').focus();
Related