rails问题与document.getElementById(" id")。focus()

时间:2015-08-19 17:05:14

标签: javascript ruby-on-rails coffeescript

嘿伙计们我试图让输入框在页面加载时获得焦点。这样用户可以简单地开始在框中键入而不用标签。此外,如果您有coffeescript版本,我也很乐意看到它。谢谢!

我在mailer.js文件中有这个:

document.getElementById("id").focus()

process_order.html.erb中的这个html

<%= form_tag(:action => 'process_orders', :method => "get") do %>
<%= text_field_tag :id %>
<%= submit_tag "Search", :name => nil %>
<% end %>

以下是页面的源代码

<form action="/process?method=get" accept-charset="UTF-8" method="post"><input name="utf8" type="hidden" value="&#x2713;" /><input type="hidden"  name="authenticity_token"  value="JE2OKhdKm+vgUufwB8mIcPtVQgTAktzahT1MkLGvDbVWb+b5mTuAyZ1L6ATgcWy9l8285R21Qqm KWt/BCt4/QA==" />
 <input type="text" name="id" id="id" />
 <input type="submit" value="Search" />
 </form></br>

2 个答案:

答案 0 :(得分:0)

您可以将autofocus属性添加到文本字段中。只需改变

<%= text_field_tag :id %>

<%= text_field_tag :id, nil, autofocus: true %>

你应该得到所需的功能。

答案 1 :(得分:0)

autofocus是HTML5属性,所有浏览器可能都不支持

您可以将焦点设置在window.onload事件

window.onload = function() {
  document.getElementById("id").focus();
}

这是coffeescript版本

window.onload = ->
  document.getElementById('id').focus()
  return