I have a multi-step form on my website that consists of several modals. Each time I click "next," it triggers the next modal and submits form data. I am currently working on implementing validation for these modals, where I want to prevent the activation of the next modal if there is missing data or reload the current modal in case of an error. Despite showing that an error exists in my ajax call, using
$('#Modal_2_Toggle').modal('show');
to reload the specific modal with the error allows the user to proceed to the next modal. I need assistance in blocking the loading of the next modal until data.error
is false. Below is the HTML code for the modal in question:
<div class="modal fade" id="Modal_2_Toggle" aria-hidden="true" aria-labelledby="Modal_2_ToggleLabel" tabindex="-1">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="Modal_2_ToggleLabel">Question 2</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<div class="progress">
<div class="progress-bar" role="progressbar" style="width: 18%;" aria-valuenow="25" aria-valuemin="0" aria-valuemax="100">18%</div>
</div>
<form method="POST" enctype="multipart/form-data", id="form_2">
{{ form_2.csrf_token }}
<p>
<br>
{{ form_2.consumption.label(class="form-label") }}
{{ form_2.consumption(class="form-control form-control-sm", id="consumptionInput") }}
</p>
{{ form_2.submit(class="btn btn-primary", id="form_2_submit", hidden="true") }}
<br>
</form>
<div id="errorAlert" class="alert alert-danger" role="alert" style="display:none;"></div>
</div>
<div class="modal-footer">
<button class="btn btn-primary modal_btn" data-bs-target="#Modal_1_Toggle" data-bs-toggle="modal" data-bs-dismiss="modal">Previous</button>
<button class="btn btn-primary modal_btn" data-bs-target="#Modal_3_Toggle" data-bs-toggle="modal" data-bs-dismiss="modal" form="form_2" id="modal_2_confirm">Next</button>
</div>
</div>
</div>
</div>
Here is my JavaScript code:
$(document).ready(function() {
$('#form_2').on('submit', function(event) {
$.ajax({
data : {
consumption : $('#consumptionInput').val(),
},
type : 'POST',
url : '/test'
})
.done(function(data){
if (data.error) {
$('#errorAlert').text(data.error).show();
$('#Modal_2_Toggle').modal('show'); <- I ASSUMED THIS WOULD RELOAD THE MODAL
}
});
event.preventDefault();
});
});