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
It looks like this line should be changed:
To this one:
Or hide the modal through JavaScript inside your
save()
function: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.
To reset the form before each use, add another event listener for Bootstrap’s show modal event:
click to enlarge
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:
The demo includes the above modification and also other minor changes which you may want to make to your code.