Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

event.preventDefault does not prevent default action #514

Open
theghall opened this issue Jan 28, 2019 · 0 comments
Open

event.preventDefault does not prevent default action #514

theghall opened this issue Jan 28, 2019 · 0 comments

Comments

@theghall
Copy link

theghall commented Jan 28, 2019

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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant