I have a Boostrap 5 form with validations and when I add the data-bs-target attribute to send button the modal is triggered even if the form has invalid entires. I want to make the model triggered only when the form is successfully validated. I tried it with javascript but my code didn't work Below is my approach:
<div class="form-button mt-3">
<button id="submit" type="submit" class="site-btn " data-bs-toggle="modal" data-bs-target="">Send</button>
</div>
<script type="text/javascript">
(function() {
'use strict'
const forms = document.querySelectorAll('.requires-validation')
Array.from(forms)
.forEach(function(form) {
form.addEventListener('submit', function(event) {
if (!form.checkValidity()) {
event.preventDefault()
event.stopPropagation()
}
form.classList.add('was-validated'),
document.getElementById('submit').dataset.target ='#confrimationModal';
}, false)
})
})()
</script>
You may programmatically open modal
const modal = new bootstrap.Modal(document.getElementById('confrimationModal'));
modal.show();
instead of
document.getElementById('submit').dataset.target ='#confrimationModal';
ref https://getbootstrap.com/docs/5.0/components/modal/#via-javascript
data-bs-target(function() {
'use strict'
document.addEventListener('submit', function(event) {
const tgt = event.target;
if (tgt.matches(".requires-validation") && !tgt.checkValidity()) {
event.preventDefault()
event.stopPropagation()
} else {
tgt.classList.add('was-validated');
document.getElementById('submitButton').dataset.bsTarget = '#confirmationModal';
}
})
})()
<div class="form-button mt-3">
<button id="submitButton" type="submit" class="site-btn" data-bs-toggle="modal" data-bs-target="">Send</button>
</div>