【问题标题】:How to focus form input field with Rails + Bootstrap + formtastic_bootstrap如何使用 Rails + Bootstrap + formtastic_bootstrap 聚焦表单输入字段
【发布时间】:2014-05-02 12:38:42
【问题描述】:

我有一个输入表单,我想在页面加载时设置键盘焦点。我正在使用带有 Bootstrap 的 Rails,并且我有 formtastic_bootstrap 用于表单。这是一个简化的例子:

<%= semantic_form_for item, url:url_for_event(:create) do |f| %>
  <%= f.input :title, label: t('.title') %>
  <%= f.input :description, label: t('.description') %>
  <%= f.submit t('.create'), class: 'btn btn-primary pull-right' %>
<% end %>

我想聚焦“标题”字段,以便光标位于该字段中,并且在页面加载时会出现 Bootstrap 蓝色突出显示,以便用户可以开始在该字段中输入。

我尝试过像这样在字段上设置“自动对焦”

<%= f.input :title, label: t('.title'), input_html: { autofocus: true } %>

我用 jquery 试过了

<%= javascript_tag "$('item_title').focus()" %>

我已经尝试过使用 Javascript

<script type="text/javascript">
  document.getElementById("item_title").focus();
</script>

没有任何作用。我正在使用 Firefox 28 浏览器进行测试。我已经看到很多例子表明这些方法应该有效。这里没有其他内容 - 这是由控制器操作呈现的基本形式。它没有使用 Bootstrap 模式。

我已经通过使用 Javascript 设置其值来检查 input_title 是该字段的 ID - 这有效。

非常感谢任何建议。

【问题讨论】:

  • 你试过class: "form-control"

标签: ruby-on-rails twitter-bootstrap formtastic


【解决方案1】:

试试这个

<%= f.input :title, label: t('.title'), input_html: {:autofocus => true} %>

【讨论】:

    【解决方案2】:

    只需将类添加到您的 div 中

    <%= f.input :title, label: t('.title'), class: "form-control"  %>
    

    【讨论】:

    • 试过了,给出了 html &lt;input id="item_title" class="form-control" type="text" name="item[title]" maxlength="255"&gt;&lt;/input&gt; 但它似乎没有做任何事情。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-09-29
    • 2019-04-15
    • 2020-07-19
    • 2013-01-28
    • 2013-01-02
    • 2017-09-12
    • 1970-01-01
    相关资源
    最近更新 更多