skip to Main Content

I am learning HTML, CSS, JS and PHP and put on myself to make a page with lets the user leave a message, but i have not being able to implement a way to make the modal close after the user correctly submits the form.

here is the part of the CODE:

[...]
<div class="modal fade" id="messagebook" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
          <div class="modal-dialog modal-dialog-centered modal-dialog-scrollable modal-lg">
            <div class="modal-content">
              <div class="modal-header">
                <h1 class="modal-title fs-5" id="staticBackdropLabel">Write a message:</h1>
                <button type="button" class="btn-close" onclick="clearForm()" data-bs-dismiss="modal" aria-label="Close"></button>
              </div>
              <form onsubmit="event.preventDefault(); save();">
                <div class="modal-body">
                  <fieldset>
                    <input type="hidden" id="id">
                    <div class="book">
                      <label for="user">User:</label><br>
                      <input type="text" id="user" name="user" required>
                    </div>
                    <div class="book">
                      <label for="email">E-mail:</label><br>
                      <input type="email" id="email" name="email" required>
                    </div>
                  </fieldset>
                  <fieldset>
                    <div class="book">
                      <label for="message">Message:</label><br>
                      <textarea type="text" id="message" name="message" rows="5" cols="30" required></textarea>
                    </div>
                  </fieldset>
                </div>
                <div class="modal-footer">
                  <button type="submit" id="sub" class="but">Send</button>
                </div>
              </form>
            </div>
          </div>
        </div>
      </section>
    </main>
    <br>
[...]
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz" crossorigin="anonymous"></script>
    <script src="SiteAjs.js"></script>
[...]

2

Answers


  1. It looks like this line should be changed:

    <button type="submit" id="sub" class="but">Send</button>
    

    To this one:

    <button type="submit" id="sub" class="but" data-bs-target="#messagebook" data-bs-dismiss="modal">Send</button>
    

    Or hide the modal through JavaScript inside your save() function:

    // Just for reference (can be outside the save function)...
    const myModal = new bootstrap.Modal(document.getElementById('messagebook'), {
      keyboard: false
    });
    
    // Should be inside your save function:
    myModal.hide();
    
    Login or Signup to reply.
  2. Use Bootstrap’s modal.hide() method after data validation

    You need to add code to handle form submit. This event happens after the send button has been clicked and after the browser has validated the data. At this point you can closed the modal and do something with the form. Importantly, you do not want to close the modal when the button is clicked because this happens before the form has been validated.

    form.addEventListener('submit', (e) => {
        modal.hide();
        // do something with the form data
    })
    

    To reset the form before each use, add another event listener for Bootstrap’s show modal event:

    element.addEventListener('show.bs.modal', (e) => {
      form.reset();
    })
    

    click to enlarge

    screenshot

    There are multiple other problems with your code. The most serious is that it encloses both the modal body and footer within the form. this breaks Bootstrap’s modal-dialog-scrollable style that you’ve applied. To fix this, move the form inside the modal body. The submit button can remain in the footer, but reconnected to the form using the form attribute like so:

    <div class="modal-body">
      <form id="message-form" method="dialog">
        ...
      </form>
    </div>
    <div class="modal-footer">
      <button type="submit" form="message-form">Send</button>
    </div>
    

    The demo includes the above modification and also other minor changes which you may want to make to your code.

    // wait for the document to load
    document.addEventListener('DOMContentLoaded', () => {
    
      // get the host element, modal, and form
      const element = document.getElementById('messagebook');
      const form = element.querySelector('form');
      const modal = bootstrap.Modal.getOrCreateInstance(element);
      
      // hide modal after form validation
      form.addEventListener('submit', (e) => {
        modal.hide();
    
        console.log('OK - Form Validated');
        for (const pair of new FormData(form).entries()) {
          console.log(pair[0], pair[1]);
        }
    
      })
      
      // optional - reset form before show
      element.addEventListener('show.bs.modal', (e) => {
        form.reset();
      })
    
      // auto show for demo
      modal.show();
    
    })
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" ">
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js "></script>
    
    
    <!-- Button trigger modal -->
    <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#messagebook">
      Show Modal
    </button>
    
    
    <div class="modal fade" id="messagebook" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
      <div class="modal-dialog modal-lg modal-dialog-centered modal-dialog-scrollable">
        <div class="modal-content">
          <div class="modal-header bg-primary text-light" data-bs-theme="dark">
            <h1 class="modal-title fs-5">Write a message:</h1>
            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
          </div>
          <div class="modal-body">
            <form id="message-form" method="dialog">
              <input type="hidden" name="id" value="100">
              <div class="form-floating mb-3">
                <input class="form-control" type="text" name="user" placeholder="Name" spellcheck="false" required>
                <label class="form-label">Name</label>
              </div>
              <div class="form-floating mb-3">
                <input class="form-control" type="email" name="email" spellcheck="false" placeholder="E-mail" required>
                <label class="form-label">E-mail</label>
              </div>
              <div class="mb-3">
                <label>Message</label>
                <textarea class="form-control" name="message" minlength="10" required rows="5"></textarea>
              </div>
            </form>
          </div>
          <div class="modal-footer bg-light">
            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
            <button type="submit" form="message-form" class="btn btn-primary">Send</button>
          </div>
        </div>
      </div>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search