Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to focus a form input field when page loaded

In my rails 3 application, I have a view haml file with a form like following:

= form_for(:car, :url => cars_path) do |f|   %p     = f.label :carname   %p       = f.text_field :carname /focus here   %p     = f.label :carnr   %p     = f.text_field :carnr   %p     = f.submit 

I would like the input field = f.text_field :carname is in focus when the page is loaded.

How to do it? Is it necessary to use jquery? or is there any Rails way to do the focus?

like image 496
Mellon Avatar asked Mar 09 '11 09:03

Mellon


People also ask

How do you set focus on input field?

To set focus to an HTML form element, the focus() method of JavaScript can be used. To do so, call this method on an object of the element that is to be focused, as shown in the example. Example 1: The focus() method is set to the input tag when user clicks on Focus button.

How do I focus a div on page load?

attr("tabindex",-1). focus(); On page load I want divVZITab to become the focus, it is in the center of page. So when page loads IE should automatically scroll to the center of the page & focus on the div.

How do you focus text input?

Input Text focus() MethodThe focus() method is used to give focus to a text field. Tip: Use the blur() method to remove focus from a text field.

How do you place the cursor automatically focus in a text box when a page gets loaded?

Sometimes all you have to do to make sure the cursor is inside the text box is: click on the text box and when a menu is displayed, click on "Format text box" then click on the "text box" tab and finally modify all four margins (left, right, upper and bottom) by arrowing down until "0" appear on each margin.


2 Answers

it isn't necessary to use jquery, but it is necessary to use javascript if you're not using HTML5 but you will have to do with jquery or javascript for now:

document.getElementById('carname').focus(); 

or

$("carname").focus(); 

with HTML5

= f.text_field :carname, :autofocus => true 

There is one caveat on the HTML5 approach: the field that you autofocus does NOT get a focus() event so any CSS styling that you do through onfocus doesn't happen.

like image 157
corroded Avatar answered Sep 21 '22 17:09

corroded


Use autofocus.

NOTE: HTML5 Only. See browser support.

= form_for(:car, :url => cars_path) do |f|   %p    = f.label :carname  %p      = f.text_field :carname, autofocus: true  %p    = f.label :carnr %p   = f.text_field :carnr %p = f.submit 
like image 28
franklinexpress Avatar answered Sep 19 '22 17:09

franklinexpress