简体   繁体   English

如何触发远程表单以在 Enter 上提交(Rails6)

[英]How can I trigger a remote form to submit on Enter (Rails6)

I have a challenging situation where I have comment form with textarea and a Comment button but I want to submit the comment on Enter rather than the user having to click the button.我有一个具有挑战性的情况,我有带有 textarea 和 Comment 按钮的评论表单,但我想在 Enter 上提交评论,而不是用户必须单击按钮。

This is further complicated by the fact that it is a nested comments structure so at any point in time there may be more than one Comment form on the page .由于它是一个嵌套的评论结构,因此在任何时候页面上都可能有多个评论表单,这使情况变得更加复杂。

I have tried looking at other examples but so far either the form does not submit (when I use requestSubmit, or if I try trigger('submit') or trigger('submit.rails') it submits as HTML and not JS.我已经尝试查看其他示例,但到目前为止,表单没有提交(当我使用 requestSubmit 时,或者如果我尝试 trigger('submit') 或 trigger('submit.rails') 它提交为 HTML 而不是 JS。

My form looks like so:我的表格如下所示:

<%= form_for [commentable, Comment.new], remote: true do |f| %>
      <%= f.text_area :body, class: "form-control comment", style: "width: 100%;", rows: "1",
        placeholder: "Add your comments" %>
      <%= f.submit 'Send', class: "form-control btn btn-sm btn-outline-primary mb-2 comment" %>
<% end %>

And my javascript (in javascript/packs/application.js) currently looks like:我的 javascript(在 javascript/packs/application.js 中)目前看起来像:

  $('textarea.comment').on('keyup keypress', function(event) {
    if (event.which == 13 && !event.shiftKey) {
      $('form').trigger('submit.rails')
     }
  });

(I've tried other variants, as mentioned). (如前所述,我尝试了其他变体)。

I've also added some other includes at the top of my application.js per other examples:根据其他示例,我还在我的 application.js 顶部添加了一些其他包含:

//= require jquery
//= require jquery_ujs

Any assistance would be appreciated.任何援助将不胜感激。

-- --

To clarify yes this is Rails 6 and yes a key press does trigger correctly as verified by console.log s which I've removed for the sake of brevity.为了澄清是的,这是Rails 6,是的,按键确实触发了console.log的验证,为简洁起见,我已将其删除。

Try triggering a click on the submit button which should trigger the Rails UJS event handler indirectly:尝试触发点击提交按钮,这应该会间接触发Rails UJS 事件处理程序

// Use a delegated handler for compatiblity with Turbolinks
$(document).on('textarea.comment', 'keyup keypress', function(event) {
  if (event.which == 13 && !event.shiftKey) {
    $(this.form).find("input[type='submit']").click();
  }
});

Okay for better or for worse this is working:好吧,无论好坏,这都是有效的:

$(document).on('turbolinks:load',function() {
  $('#comments_container').on('keyup keypress', 'textarea', function(event) {    
    if (event.which == 13 && !event.shiftKey) {
      event.preventDefault();
      let target = event.target; // target is the textarea
      $(target.form).find("input[type=submit]").trigger('click')
    }
  });

...

});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM