Preventing form submission not working?
See original GitHub issueI’m actually not sure if this is a Stimulus or rails_ujs problem, but I setup a simple controller to prevent a form submission if the text was too long like Twitter’s form. preventDefault()
didn’t work and Rails just submitted the form anyways. Any ideas on how to make this work?
<%= form_with(model: tweet, data: { controller: "tweet-form", action: "submit->tweet-form#submit" }) do |form| %>
<%= form.text_area :body, data: { target: "tweet-form.body" } %>
<% end %>
import { Controller } from "stimulus"
export default class extends Controller {
static targets = [ "body" ]
submit(event) {
if (this.bodyTarget.value.lenth > 140) {
event.preventDefault() // Doesn't do anything
console.log("This tweet is too long.") // prints out
}
}
}
Issue Analytics
- State:
- Created 6 years ago
- Reactions:3
- Comments:5 (2 by maintainers)
Top Results From Across the Web
Prevent form from submitting via event.preventDefault(); not ...
If the only thing you need to do is to prevent the default action, you can supply false instead of a function: $('#form').submit(false);....
Read more >How to stop form submission using JavaScript?
We can stop the form from submission by giving the "return false;" value to the onsubmit event. Giving this value to the event...
Read more >[Solved] Preventdefault not working
I have a form that has a submit button in it somewhere. However, I would like to somehow 'catch' the submit event and...
Read more >Troubleshooting form issues
If a visitor tries to submit multiple forms through a form block in a short amount of time, an "Unknown error, please try...
Read more >How to prevent buttons from causing a form to submit with ...
I often see people use JavaScript to detect those buttons, and run event.preventDefault() to stop the default form submit behavior from running.
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
You don’t seem to have added any actions to your form element. Add one that calls the
submit
method when theajax:beforeSend
event is dispatched:@richjdsmith “starting from Rails 5.2 when using form_with it is by defaut remote. If you want to post your form in html format you must specify local: true” not sure if that helps