Focusing first control in the form using jquery Focusing first control in the form using jquery jquery jquery

Focusing first control in the form using jquery


$('form:not(.filter) :input:visible:enabled:first').focus()

This will select the first visible input element (<input />, <select>, <textarea>) that doesn't have the class filter in it.


For the background I used the script in ruby on rails app.After trying all your answer and found out they all doesn't works,With a search on google i found this snippet that works:

$(function() {  $("form:not(.filter) :input:visible:enabled:first").focus();});

It turn out $('form :input:first') match the hidden input that rails insert on every form.


I like to mark my chosen element with a class and select by class rather than leaving it up to the order of the elements on the page. I find this much easier than trying to remember to update my "what's the real first element" algorithm when selecting elements that may or may not be hidden, may or may not be injected by the framework, ...

  $(document).ready( function() {     $('input.js-initial-focus:first').focus(); // choose first just in case  });