Stimulus: Preventing form submission not working?

Created on 27 Feb 2018  路  5Comments  路  Source: hotwired/stimulus

I'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
    }
  }
}

Most helpful comment

You don鈥檛 seem to have added any actions to your form element. Add one that calls the submit method when the ajax:beforeSend event is dispatched:

<%= form_with(model: tweet, class: local_assigns[:class], data: { controller: "tweet-form", target: "inline-edit.form", action: "ajax:beforeSend->tweet-form#submit" }) do |form| %>

All 5 comments

You don鈥檛 seem to have added any actions to your form element. Add one that calls the submit method when the ajax:beforeSend event is dispatched:

<%= form_with(model: tweet, class: local_assigns[:class], data: { controller: "tweet-form", target: "inline-edit.form", action: "ajax:beforeSend->tweet-form#submit" }) do |form| %>

I just updated the code. Pasted the wrong thing. :)

Good call on ajax:beforeSend. I hadn't thought of that and it works like a charm. 馃憤

Do we have to use ajax:beforeSend instead of submit event then because the new rails_ujs implementation? I know we used to be able to preventDefault on submit with jQuery back with jquery_ujs.

Closing since this isn't a Stimulus issue. Feel free to post your question on https://discourse.stimulusjs.org/ to continue discussing.

@excid3 Did you ever resolve this? Does the new rails form_with require ajax:beforeSend instead of prevent.default()?

@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

Was this page helpful?
0 / 5 - 0 ratings

Related issues

dwightwatson picture dwightwatson  路  3Comments

saneef picture saneef  路  4Comments

joeybeninghove picture joeybeninghove  路  4Comments

adrienpoly picture adrienpoly  路  3Comments

pherris picture pherris  路  3Comments