Reputation: 3794
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?
Upvotes: 14
Views: 11483
Reputation: 63
$( document ).on('turbolinks:load', function() {
document.addEventListener("keydown", function (e) {
if (13 == e.keyCode) {
event.preventDefault();
return false;
}
});
});
Upvotes: 0
Reputation: 76774
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?
Upvotes: 33
Reputation: 5962
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
Upvotes: 1