Set Focus on First Field with jQuery

Sam Deering
Share

This is how you “Set Focus on First Field with jQuery!”

This is a simple snippet of code that sets focus with the mouse cursor in the first field of a form on a webpage as soon as it is loaded. It works in Internet Explorer, Firefox and Safari browsers.

You may think this code works but it doesn’t set the cursor in the input box:
$(‘#input’).focus();

Instead use this code this will work properly:

//set focus to first input box
        $('#input').focus();
	$("#input:text:visible:first").focus();

input-first-field-jquery

See Live Demo

Event Handler
This is how you can add an event handler to catch when a user clicks the input field.

$('#target').focus(function() {
  alert('Handler for .focus() called.');
});

Useful HTML

< !DOCTYPE html>


  
  


  

focus fire

focus fire