Thursday, April 25, 2024
HomeJavaScriptVariations between requestSubmit() and submit() in HTML varieties – Js Craft

Variations between requestSubmit() and submit() in HTML varieties – Js Craft


Probably the most used strategy to programmatically submit an HTML kind with Javascript is the submit technique:

<kind>   
  <enter required title="e-mail" id="e-mail" sort="e-mail" placeholder="E-mail right here ...">
  <enter sort="submit" class="submit-btn" worth="Use submit()" />
</kind>
const kind = doc.varieties[0]
doc.querySelector('.submit-btn')
  .addEventListener('click on', () => kind.submit()
    kind.submit())

Nonetheless, it has (no less than) 2 surprising behaviors:

  1. submit will bypass the validation of the shape. Which means that the above kind will probably be subbitment even when we’ve got the required attribute set on the e-mail enter and that enter is empty.
    // submit() won't consider the required attr
    <enter required title="e-mail" id="e-mail" sort="e-mail" >
  2. if we a add addEventListener('submit') to the shape submit may also bypass it. For instance:
    kind.addEventListener('submit', e => {
    // this code won't be referred to as when utilizing submit()
    e.preventDefault()
    alert('Code after preventDefault referred to as')
    })

Now with a full browser help, requestSubmit technique goals to offer an extra predictable behaivour to our kind submisons. The requestSubmit() will consider each the native kind validation and it alows interceptions with addEventListener('submit').

kind.addEventListener('submit', e => {
  // this will probably be referred to as solely 
  // when utilizing requestSubmit()
  e.preventDefault()
  alert('Code after preventDefault referred to as')
})

doc.querySelector('.submit-btn')
  .addEventListener('click on', () => kind.submit()
    kind.submit())

// requestSubmit() will first examine for kind validation
doc.querySelector('.requestSubmit-btn')
  .addEventListener('click on', () => kind.requestSubmit())

Checkout a working codepen right here.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments