Utilizing the power of Bootstrap 5
I have successfully implemented a modal that shows up when #truck_modal
is clicked, thanks to the following JavaScript code:
(this snippet is located at the beginning of my js file)
document.addEventListener('DOMContentLoaded', function() {
document.querySelector('#add_truck').addEventListener('click', AddTruck);
const truck_modal = document.querySelector('#staticBackdrop');
const modal = new bootstrap.Modal(truck_modal, {
backdrop: 'static'
});
document.querySelector('#truck_modal').addEventListener('click', () => {
modal.show();
});
})
However, I encountered a challenge when trying to make the modal hide only if the AddTruck
function is successful. Here's my attempt:
function AddTruck() {
... performing some validations ...
fetch('/inbound/add_truck', {
... fetching data ...
})
.then(response => {
jsonResponse = response.json();
status_code = response.status;
if(status_code != 200) {
alert('There was an error!');
} else {
origin.value = '';
produce.value = '';
license_num.value = '';
loaded_weight.value = '';
modal.hide();
alert('Success!!!')
}
return status_code
})
.catch(error => {
console.log(error)
})
}
Despite several attempts, including creating a separate function to hide the modal, I still face issues. Any suggestions on how to solve this problem would be highly appreciated.
Could this be a built-in feature of Bootstrap or am I missing something important?
UPDATE
Below are the JS scripts, Bootstrap, and jQuery included in my project:
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="096b66667d7a7d7b6879493c27392739246b6c7d683b">[email protected]</a>/dist/js/bootstrap.bundle.min.js" integrity="sha384-b5kHyXgcpbZJO/tY9Ul7kGkf1S0CWuKcCD38l8YkeH8z8QjE0GmW1gYU5S9FOnJ0" crossorigin="anonymous"></script>
<script src="{% static 'utils.js' %}"></script>
In an effort to hide the modal, I also added the line $('#truck_modal').modal('hide');
within the else block of my code.