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?
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?
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