rails / jquery-ujs

Ruby on Rails unobtrusive scripting adapter for jQuery
MIT License
2.61k stars 508 forks source link

event.preventDefault does not prevent default action #514

Open theghall opened 5 years ago

theghall commented 5 years ago

I have a form_for as follows: <%= form_for @new_house.house, url: houses_path, remote: true, html: { id: 'subscribe-form' } do |f| %>

I have a class which adds a listener to the form when onSubmitForm is called:

class HousesNewSubscribeListeners {
  constructor() {
    this.$subscribeForm = document.getElementById('subscribe-form')
    this._initializeStripeService()
  } 

  onSubmitForm() {
    this.$subscribeForm.addEventListener('submit', (event) => {
      event.preventDefault()
      this.stripeService.createToken()
        .then((response) => {
          this._handleStripeResponse(response)
        }).catch((err) => {
          Toast.render(err)
        })
    })
  }

 _handleStripeResponse(response) {
    if (response.error) {
      const errorElement = document.getElementById('card-errors')
      errorElement.textContent = response.error_message
    } else {
      this._addTokenToForm(response.token.id)
      Rails.fire(this.$subscribeForm, 'submit')
  }

The default action still fires though. I've tried the following as well: 1) preventDefault + stopPropagation with the result that the default action is not fired but Rails.fire does nothing but the event listener keeps getting executed in an endless loop. 2) return false with the result that the default action fires, which is weird since it is equivalent to above. 3) stopPropagation with the result that the default action fires, but submits a request to the server expecting HTML, not JS.