13

Simple example:

 <%= form_for :post, url: posts_path  do |f|%>
    <p>
        <%= f.label :title%><br/>
        <%= f.text_field :title%>
    </p>
    <p>
        <%= f.label :text%><br/>
        <%= f.text_area :text%>
    </p>
    <p>
        <%= f.submit%>
    </p>
<%end%>

I think this is a Rails default event handling. In here, if the user presses the enter key, it submits the params.

But in my case, I have to use the enter key for another event.

I have to search users with another input field by pressing the enter key.

But if I use form_for it submits the form. :(

How can I prevent submitting with the enter key in rails?

Do I have to use plain html tags? Like <form> tag and <submit> button?

Any good solutions?

Ryan K
  • 3,985
  • 4
  • 39
  • 42
Canna
  • 3,614
  • 5
  • 28
  • 33

2 Answers2

30

Enter key submit is not a rails problem, it's an HTML / JS problem

Rails is backend (lives on the server); HTML / JS are client-side (live in browser) - they determine what functionality is enabled / disabled

I would get around your problem like this:

$('form').on('keypress', e => {
    if (e.keyCode == 13) {
        return false;
    }
});

And if you're using Turbolinks:

$(document).on('turbolinks:load', () => {
    $('form').on('keypress', e => {
        if (e.keyCode == 13) {
            return false;
        }
    });
});

Good reference: How to prevent ENTER keypress to submit a web form?

Jason Swett
  • 43,526
  • 67
  • 220
  • 351
Richard Peck
  • 76,116
  • 9
  • 93
  • 147
1

This is not a Rails specific question it's since it's a native behaviour of all browsers. If you have a button submit in your form (and you should :) ) then every browser will submit the form after hitting enter. *I haven't checked, but even without a clear submit button it should do it] The accepted answer is correct, but since there is a thread that gives a more complex example I would go through it too:

Prevent users from submitting a form by hitting Enter

Community
  • 1
  • 1
luigi7up
  • 5,779
  • 2
  • 48
  • 58