【问题标题】:SimpleForm submit with "return" keySimpleForm 使用“return”键提交
【发布时间】:2015-02-28 00:55:56
【问题描述】:

使用 simple_form gem 和 rails 我试图通过点击返回键来提交 text_area(评论框)。 Facebook 也有类似的功能,而这正是我所追求的。在线研究并没有产生太多成果,而且我对 Javascript 还是很陌生。有什么建议吗?

表格部分

<%= simple_form_for [@commentable, @comment] do |f| %>
    <!-- Error messages -->
    <% if @comment.errors.any? %> 
    <div class="error_messages">
        <h2>Please correct the following errors.</h2>
        <ul>
            <% @comment.errors.full_messages.each do |msg| %>
                <li><%= msg %></li>
            <% end %>
        </ul>
    </div>
    <% end %>
    <!-- Comment Text Area -->
    <span class="field" id: "textArea">
        <%= f.text_area :content, placeholder: 'Comment...', rows: 3, class: 'story-comment' %><br/>
    </span>

    <!-- Submit Button -->
    <span class="actions" id: "formSubmit">
        <%= f.button :submit, "Post Comment", class: "btn btn-default pull-right"%>
    </span>
<% end %>

表单输出html:

<form accept-charset="UTF-8" action="/statuses/91/comments" class="simple_form new_comment" id="new_comment" method="post" novalidate="novalidate"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="&#x2713;" /><input name="authenticity_token" type="hidden" value="vSpHph2PkCPAiItJ8UJFZh8grkanJA4VQxsdcxrcvig=" /></div>
    <!-- Error messages -->
    <!-- Comment Text Area -->
    <span class="field" id: "textArea">
        <textarea class="story-comment" id="comment_content" name="comment[content]" placeholder="Comment..." rows="3">
</textarea><br/>
    </span>

    <!-- Submit Button -->
    <span class="actions" id: "formSubmit">
        <input class="btn btn btn-default pull-right" name="commit" type="submit" value="Post Comment" />
    </span>
</form>

这是我目前想出的:

 $('#textArea').keypress(function (e) {
      if (e.which == 13) {
        $('#formSubmit').submit();
        return false;
      }
    });

【问题讨论】:

  • 1) 您的 formSubmit 不是表单 - 您需要一个表单来调用 .submit() - 您需要在按钮上执行 click() 2) 呈现的 HTML 是什么样的 3) 什么如果有错误,是否在控制台中?
  • 1) 不确定如何获得呈现的 HTML。 2)控制台没有错误。 3) formSubmit 只是我添加的一个 id。我在 Rails 方面相当先进,但我不熟悉 javascript 最佳实践,所以不可否认,这部分可能是完全错误的。
  • 查看源代码以查看 html。文本区域需要带有提交操作的表单标签
  • @mplungjan 谢谢。添加了呈现的 HTML。有什么建议吗?

标签: javascript ruby-on-rails simple-form


【解决方案1】:

您需要提交 FORM 而不是按钮,并且您需要访问 textarea 的 ID

试试

$('#comment_content').keypress(function (e) {
  if (e.which == 13) {
    $('#new_comment').submit();
    return false;
  }
});

【讨论】:

  • 你并没有告诉我们一切。例如,ID 必须是唯一的,并且 ID 必须与您的脚本匹配
  • 我回到了这个问题,我假设我的 JS 中有一个语法错误,导致它无法触发。它现在工作正常,我直接复制了你的代码。谢谢!
  • 不客气。请为未来的访问者删除第一条评论
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-22
  • 1970-01-01
  • 2012-02-05
相关资源
最近更新 更多