Ways to incorporate a Javascript variable into a modalDialogContentBox

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">&times;</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>

Answer №1

If you want to display a message upon completing an action, you can use the following code in your callback function:

$(document).ready(function() {
  $(".alert-message").html("Thank you for registering!\n\nYou will receive a confirmation email shortly."); 
  $("#myModal").modal("show"); 
});

Answer №2

To display the Javascript variable (sum) in your modal, you can follow these steps: Add an empty <p> tag to your modal HTML and assign it a unique id. Then, within your script, replace the innerHTML of this tag with the value of your variable:

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) {
$(document).ready(function(){$("#myModal").modal("show"); });
return false;
}
else {
return true;
}
document.getElementById('sum').innerHTML=sum;
}
} 
<!-- 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">&times;</button>
         </div>
         <!-- Modal body -->
         <div class="modal-body">
            <p id="sum"></p> <!-- Display 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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Preventing special characters, numbers, and spaces from being used as the first character in a word in HTML with regular expressions

Is there a way to restrict users from inputting special characters, numbers, and spaces only in the first place of a word using regex in HTML? <label><span>Current Carrier</span></label> <input name='Current Carrier' t ...

Reducing the size of icons on a small screen using Bootstrap 4

Is it possible to decrease the size of icons on small screens in Bootstrap 4? I am currently working on a Bootstrap project and my aim is to reduce the size of icons specifically on smaller screens. For example, when the screen size is Mobile S-320 PX, I w ...

Utilize nested functions in Cypress instead of relying solely on a while loop

While working with Cypress, I noticed that using a while loop caused some issues. Instead of the while loop, I came up with this alternative solution: const functionName = () => { if ( a != b ) { this.functionName(); } else { cy.get(".sel ...

Whenever I use NextJS's <Link> component, I always end up getting redirected to a

After searching online, I came across this question and tried to implement the suggested solution, but it's still not working for me. Apologies for any duplication. I have a simple link tag that is resulting in a 404 error: <Link className={classe ...

Implement a unique custom mobile menu in place of the traditional WordPress default menu

Greetings! I've embarked on the journey of crafting a personalized WordPress theme using Understrap. My current mission is to replace the existing code for the mobile menu with my own creation. The problem lies in locating the file where the original ...

Running various callbacks consecutively from an array in JavaScript

I have a series of functions in an array, each one calling a callback once it's finished. For example: var queue = [ function (done) { console.log('Executing first job'); setTimeout(done, 1000); // actually an AJAX call ...

Error message: JavaScript multiline strings within backticks are currently unsupported in Internet Explorer

My HTML string, stored in a variable, is being used to populate the innerHTML. Although the first example (using backtick syntax) is simple, it does not function in Internet Explorer 11. Is there a way to make the first example work in Internet ...

Need to battle with... its own contradictions in a direct manner

I've integrated APIs for my bot, expecting them to work smoothly. However, I'm still struggling to figure out why the server keeps aborting itself... Here is the error output, code, and a screenshot. Any help would be greatly appreciated. Error: ...

There was a TypeError encountered while trying to read properties of undefined in Next.js version 13

I've encountered a problem in the title with my post API endpoint that I created in Next.js. The purpose of my endpoint is for form submission, where I gather inputs and send them to my email. Currently, my code successfully sends the email and I rec ...

You must use the 'new' keyword in order to invoke the class constructor

Although similar questions have been asked before, my situation differs from the typical scenarios. I have a basic base class named CObject structured as follows: export class CObject extends BaseObject { constructor() { super(); } sta ...

Updating the src of an iframe and adding an onclick event to a link using JavaScript

Looking to design a page that accommodates both login and sign up functionalities by dynamically updating the src of an iframe. In the navigation bar, there is: <li id="change"><a onclick="sign()">Sign up</a></li> And within the ...

Should we consider using a boolean-returning function for ng-show?

Will continuously watching a function's value or using it in a directive like ng-show have a performance impact due to the function being called each cycle? Could it be more efficient to simply use a boolean value to determine this, and update that v ...

Is it feasible to decrease the lateral margins of Bootstrap's container without the need for custom CSS? If so, what is the method?

My web page includes several screenshots to illustrate the issue I am facing. One of my challenges is the scroll bar below the table, which I find displeasing. In an attempt to resolve this, I decided to adjust the lateral margins slightly. Here's a s ...

The mysterious anomaly in Vue.js

I am attempting to assign a data object named types upon receiving a response in the ready() method. This is what I have: export default { data () { return { types: null } }, ready () { TypeService.showAll(1) .then(functio ...

React Router's default component for nested routes

In React Router, I am facing a challenge with nested Routes <Route path='about' component={{main: About, header: Header}}> <Route path='team' component={Team} /> </Route> Currently, the Team component is displayed ...

Maintain text area spacing using JavaScript

Could anyone assist me in finding a script that can change line breaks from a user's textarea input into HTML upon form submission to ensure that the formatting is maintained in our notification emails? Currently, I am encountering an issue where fie ...

Instructions on submitting a second AJAX form generated from the result of the first form submission

I loaded a form through an AJAX request in JSON format. The PHP code below generates the JSON output displaying the form: $this->errors[] = "<form id='confirmreset' name='confirm_reset' action='" . URL . "login/forgotPass ...

Experiencing a lack of information when trying to retrieve data through an http request in an express/react

Issue: My problem lies in attempting to retrieve data from http://localhost:3000/auth/sendUserData using the http protocol. Unfortunately, I am not receiving any data or response, as indicated by the absence of console logs. Tools at my disposal: The te ...

Leveraging external variables within JavaScript

In my views.py, I used to have the following structure: ... if mymodel.name == 'Myname1': #do something elif mymodel.name == 'Myname2': #do something else ... However, I found this method cumbersome because if the names change ...

Angular service is struggling to execute the FOR LOOP, but surprisingly the WHILE LOOP is functioning perfectly

This particular issue was baffling me for a while, so I decided to address it here because it's quite unusual. I attempted to cycle through a string within a service using a for loop, but unfortunately, I couldn't make it work as expected. Here ...