简体   繁体   中英

How to confirm a firm but set a function in-between?

I got a script that checks every form in my app and if there is one, that gets submitted, it will prevent the submission, toggles a loading screen and then submits the form.

<script>
  document.addEventListener('DOMContentLoaded', () => {

      const forms = document.querySelectorAll('form');
      forms.forEach((form) => {
        form.addEventListener('submit', (e) => {
          e.preventDefault();
          document.getElementById('loading').classList.toggle('hidden');
          form.submit();
        })
      });

  });

</script>

This works perfectly but for some forms (like a deletion button) I want to ask to user if this is really what he wants to do:

<form method="post" action="<?=base_url('clients/' . $meeting->cid);?>" onsubmit="return confirm('Are you sure?');">
  <input type="hidden" name="delmeeting" value="<?=$meeting->id;?>">
  <input type="submit" value="Delete" class="button">
</form>

This is in conflict with the first script. The alert gets shown correct but when I cancel it, the first script comes into place and submits.

How can I handle this?

What is important to me:

  • display the loading div every time for each form
  • having the possibility to have forms with and without a confirm window
  • keeping the code small
  • having individual texts for the confirm

Got it:

const forms = document.querySelectorAll('form');
forms.forEach((form) => {
  form.addEventListener('submit', (e) => {
    if (form.onsubmit === null) {
      e.preventDefault();
      document.getElementById('loading').classList.toggle('hidden');
      form.submit();
    }
  })
});
``

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM