Form reloads page 2nd time with preventDefault when using custom DOM function

P. Nick

I have a login form, and when submitted it calls this function

login = (that) ->
  header =
    "X-CSRFToken": window.csrftoken

  $('body').toggleDOM('.loading', true)

  fermata.json("/login").post(header, that, (err, data) ->
    $('body').toggleDOM('.loading', false)

    if !data.success
      htAlert.error 'Incorrect username and/or password.'
  )

This will add a "loading spinner" while the API is being called, and then it's removed. This works fine the first time you submit the form, because I'm using preventDefault so the page doesn't reload. However on the 2nd try, the page will reload, and I don't know why it's behaving like that.

My DOM function to add an element to the body:

$.fn.toggleDOM = (domName, b) ->
  dom = domName[domName.search(/([\.\#])/)]
  newDom = domName.substring(1)

  if dom == '#'
    if b
      document.body.innerHTML += '<div id="' + newDom + '"></div>'
    else
      document.getElementById(newDom).remove()
  else
    if b
      document.body.innerHTML += '<div class="' + newDom + '"></div>'
    else
      document.getElementsByClassName(newDom)[0].remove()

The event for form submit:

$ ->
  trigger = document.querySelectorAll("[data-trigger]")

  trigger.forEach((i) ->
     i.addEventListener "submit", (e) ->
      e.preventDefault()
      # We have to pass the event instead of the element.
      switch i.attributes["data-trigger"].nodeValue
        when "[form/login]" then login(e)

HTML:

<form data-trigger="[form/login]" class="login">
  <input type="hidden" class="uuid hidden">
  <input placeholder="Username" class="username">
  <input placeholder="Password" type="password" class="password">
  <button type="submit">Login</button>
</form>

I need to know why it reloads the page on the 2nd try. If I remove the $('body').toggleDOM('.loading', true) it does not behave like that and works as intended.

Also, I'm not using jQuery, I'm using this small library: https://github.com/finom/balalaika

Henrik Andersson

The problem lies in how you attach event listeners to your elements. What you're trying to do doesn't work in plain JavaScript.

What you need to utilize is event delegation; it won't change much code wise but it'll change how it works.

By removing your for loop and attaching the handler to the document instead, you'll get what you're after.

document.addEventListener "submit", (e) ->
  e.preventDefault();
  switch e.target.attributes["data-trigger"].nodeValue
    when "[form/login]" then login(e)

There is a great article that covers the how and why

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

How to open form 2nd time when it's closed

strange behaviour when submitting form 2nd time

Submitting form reloads the page using turbolinks

why is the c function not scanning 2nd time using scanf function?

How to printf to next line when function is executed for the 2nd time in C?

Function doesn't return variable when reassigning it a 2nd time

page reloads when updating redux state/submitting form

Using form onsubmit not firing javascript and instead reloads page

on click event of checkbox called when clicked 2nd time using jquery

vuejs not rending data 2nd time when data as updated using ajax

What is the default caching time when using Hibernate's 2nd level cache

Is there a way of submitting this form after using the preventDefault function?

Asynchronous function makes request without data when page reloads

How to know the type of the event when using cloud function 2nd gen?

Django form validation fails when using second unmanged database / How to use 2nd DB for form validation?

State not updating until 2nd time the form is submitted

Magento - custom module add 2nd page

persisting layouts when page reloads

How to call/echo php function on 2nd php page

Function to make copy of 2nd page of PDF(s) is failing

Bootstrap Modal appearing empty when reopened for a 2nd time

Infinite Loop 2nd time around using scanner

How to get the 2nd last row inserted using time?

Error when deploying 2nd gen Firebase Cloud Function

Pandas apply function when database is the 2nd positional argument

Custom Pagination using Angular JS- Need to display div elements in first page which should get repeated on 2nd page clicked Next

Matlab: Solve 2nd order ODE using anonymous function

Why a form tag without action reloads the page?

Popup disappears and page reloads on form submit