Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent enter key submit in rails

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?

like image 980
Canna Avatar asked Dec 24 '13 09:12

Canna


1 Answers

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?

like image 68
Richard Peck Avatar answered Sep 25 '22 02:09

Richard Peck