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开发者_StackOverflow |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?
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.
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
精彩评论