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?
To submit the form using 'Enter' button, we will use jQuery keypress() method and to check the 'Enter' button is pressed or not, we will use 'Enter' button key code value. Explanation: We use the jQuery event. which to check the keycode on the keypress.
The form can be submitted without using submit button by implementing a specific event attribute or by clicking the link. This task can be done by using the OnClick event attribute or by using the form. submit() method in Javascript.
HTML form submit on Enter Key | Example code You don't need to use JavaScript to do submit button or input on entering key pressed. Just need to mark it up with type="submit" , and the other buttons mark them with type="button" .
Using JavaScript In vanilla JavaScript, you can bind an event handler to the keyup event using the addEventListener() method and use the KeyboardEvent. code property to determine whether an Enter key is pressed. Finally, trigger the form's submit event on Enter keypress.
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();
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With