Focusing the First Field in Form using jQuery

Leave a Comment

Normally, to begin filling out a form, you have to click into the first text field and start typing. On a page with a login form, why make your visitors go to the extra trouble of moving their mouse into position and clicking into the login field before they can type? Why not just place the cursor in the field, ready to accept their login information immediately? With JavaScript, that’s a piece of cake.

The secret lies in focus, which isn’t just an event JavaScript can respond to but a command that you can issue to place the cursor inside a text field. You simply select the text field, and then run the jQuery focus() function. So the JavaScript to place the focus on - that is, place the cursor in - that field looks like this:
$(document).ready(function() {
$('#username').focus();
});

In this example, the text field has the ID username. However, you can also create a generic script that always focuses the first text field of a form, without having to assign an ID to the field:
$(document).ready(function() {
$(':text:first').focus();
});

jQuery provides a convenient method of selecting all text fields - $(‘:text’). In addition, by adding :first to any selector, you can select the first instance of that element, so the jQuery selector $(‘:text:first’) selects the first text field on the page. Adding .focus() then places the cursor in that text field, which waits patiently for the visitor to fill out the field.

If you have more than one form on a page (for example, a “search this site” form, and a “sign up for our newsletter” form), you need to refine the selector to identify the form whose text field should get focus. For example, say you want the first text field in a sign up form to have the cursor blinking in it, ready for visitor input, but the first text field is in a search form. To focus the sign up form’s text field, just add an ID (signup, for example) to the form, and then use this code:
$(document).ready(function() {
$('#signup :text:first').focus();
});

Now, the selector - $(‘#signup :text:first’) - only selects the first text field inside the sign up form.

0 comments:

Post a Comment