How to prevent an input key from entering the rails

A 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 Rails default event handling. Here, if the user presses the enter key, he sends params .

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

I need to search for users with a different input field by pressing the enter key.

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

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

Do i need to use simple html tags? Like the <form> tag and <submit> button ?

Any good solutions?

+11
jquery ruby-on-rails
source share
2 answers

Entering an input key is not a rails issue, but an HTML / JS issue

Rails is a backend (lives on the server); Client-side HTML / JS (real-time in the browser) - they determine which features are enabled / disabled

I would go around your problem like this:

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

And if you use Turbolinks:

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

Useful link: How to prevent the ENTER key from being pressed when submitting a web form?

+21
source share

This is not a specific Rails question as it is the natural behavior of all browsers. If you have a submit button in your form (and you should :)), then each browser will submit the form after entering it. * I didn’t check, but even without a clear submit button, he should do it] The accepted answer is correct, but since there is a stream that gives a more complex example, I would also go through it:

Prevent users from submitting a form by pressing Enter

+1
source share

All Articles