SimpleForm 使用 "return" 键提交

SimpleForm submit with "return" key

使用 simple_form gem 和 rails 我试图通过按 return 键来提交 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;
      }
    });

您需要提交表单而不是按钮,并且您需要访问文本区域的 ID

尝试

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