In my search for a JavaScript solution, I came across a code that calculates the sum of input fields with the class "qt" when a form is submitted. If the total sum is less than 15, a message is displayed in a JavaScript alert popup. While this functionality works fine, I am not a fan of the default style of the alert popup and unfortunately, it cannot be easily styled. Therefore, I decided to implement the message in a more visually appealing modal dialog. The process seemed promising until I encountered an issue: I couldn't find a way to transfer the value of the JavaScript variable (sum) into the modal window and display it there.
Here is the form tag:
<form onsubmit="return calculateSum(this);" method="post" name="order" id="order" action="confirm.php">
This is the JavaScript function (stored externally in javascript.js):
function calculateSum() {
var sum = 0;
//iterate through each textboxes and add the values
$(".qt").each(function() {
//add only if the value is number
if(!isNaN(this.value) && this.value.length!=0) {
sum += parseFloat(this.value);
}
});
if(sum<15) {
//alert('Please order at least 15 boxes.\n\nYour current selection is ' + sum + '.');
$(document).ready(function(){$("#myModal").modal("show"); });
return false;
}
else {
return true;
//return confirm('Do you really want to submit the form?');
}
}
Below is the HTML snippet for the Bootstrap modal I intend to use:
<!-- The Modal -->
<div class="modal fade" id="myModal">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<h4 class="modal-title">Modal Heading</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<!-- Modal body -->
<div class="modal-body">
<!--HOW CAN I SHOW THE JAVASCRIPT VARIABLE (sum) HERE?-->
</div>
<!-- Modal footer -->
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>