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?
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.
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With