Skip to main content

Set Focus on First Field with jQuery

By Sam Deering

JavaScript

Share:

Free JavaScript Book!

Write powerful, clean and maintainable JavaScript.

RRP $11.95

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

Sam Deering has 15+ years of programming and website development experience. He was a website consultant at Console, ABC News, Flight Centre, Sapient Nitro, and the QLD Government and runs a tech blog with over 1 million views per month. Currently, Sam is the Founder of Crypto News, Australia.

New books out now!

Learn valuable skills with a practical introduction to Python programming!


Give yourself more options and write higher quality CSS with CSS Optimization Basics.