Skip to content

event.preventDefault does not prevent default action #514

Open
@theghall

Description

@theghall

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions