Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 4: how to allow user to submit form with enter key, without submit button

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?

like image 298
Thibaud Clement Avatar asked Oct 08 '15 23:10

Thibaud Clement


People also ask

How do you submit a form when Enter key is pressed?

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.

Can a form submit without button?

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.

How do I make a form so it can be submitted by hitting Enter in HTML?

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" .

How do you set enter key as submit form in JavaScript?

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.


1 Answers

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();
       }
    });
like image 170
mahi-man Avatar answered Sep 28 '22 08:09

mahi-man