How to Set focus on First textbox of page using jQuery

In any webpage where there are lots of input controls and you want the foucs on the first text box when the page is loaded. It is a piece of cake with jQuery. See below code.

$(document).ready(function() {
    $('input:text:first').focus();
});
See live Demo and Code.

But there could be one problem with this approach, if you first textbox is disabled. Well, again piece of cake with jQuery.

$(document).ready(function() {
    $('input[type=text]:enabled:first').focus();
});
See live Demo and Code.

Cool, isn't it. Another problem, my first textbox is not visible (display:none) then what should I do?

<input type='text' id='txtFirstName' style='display:none' />

Not to worry, as we have jQuery. :)

$(document).ready(function() {
    $('input[type=text]:visible:first').focus();
});
See live Demo and Code.

The best method is to set the focus using ID of the control as you know that control is visible and it is not disabled.

$(document).ready(function() {
    $('#txtFirstName').focus();
});

Feel free to contact me for any help related to jQuery, I will gladly help you.



Responsive Menu
Add more content here...