JavaScript: How to set focus to form elements?

Normally, when users click on any label tag with the cursor, the corresponding input field will be focused ready for input or selection. Therefore, you can always achieve the focus effect by this native function of HTML’s. Otherwise, you’d need a small dime of JavaScript to set focus to any form element on the fly upon a certain event:

// FormName is the name value of the form.
// FieldName is the name value of the field
// to be focused.
document.FormName.FieldName.focus();

Or by element ID:

// FieldId is the id value of the field
// element to be focused.
document.getElementById('FieldId').focus();

There you go, the tiny focus() function is what we all need.

Scroll to Top