Reputation: 121
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.
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.
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:
$('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:
//= 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.
Upvotes: 1
Views: 1050
Reputation: 121
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')
}
});
...
});
Upvotes: 0
Reputation: 102036
Try triggering a click on the submit button which should trigger the Rails UJS event handler indirectly:
// 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();
}
});
Upvotes: 1