Reputation: 6897
I have a Rails 4, that uses Rails' default form (I am NOT using Simple Form).
—————
EDIT: although the goal is fairly similar (allowing users to submit a form by pressing the enter key instead of pushing a submit button), my question is different from Form submitting when pressing enter in Textarea since it relates to Rails forms, which have a particular behavior and do not work in the same way as regular jQuery forms.
—————
One of my forms allows users to create comments:
<%= form_for([post, post.comments.build]) do |f| %>
<p>
<%= f.text_area :body, :placeholder => "New comment", size: "15x1" %><%= f.submit id: 'create_comment'%>
</p>
<% end %>
I would like to get rid of the <%= f.submit id: 'create_comment'%>
part and allow users to submit a new comment just by pressing the enter key.
How can this be achieved?
Upvotes: 5
Views: 7000
Reputation: 4676
If you use a f.text_field rather than text_area it should submit the form on enter by default.
If you need to use a textarea, then it will have to be javascript. something like:
$('#id_of_textarea').keypress(function(e){
if(e.which == 13){
$(this).closest('form').submit();
}
});
Upvotes: 10