JavaScript is reliant on the presence of the alert() function to properly function

I have a JavaScript function that performs well, except for when I remove or comment out the alert() line. This function is designed to calculate the sum of values in up to 30 fields if they are present and contain a value.

Here is an example of the HTML structure:

<input type="text" onblur="Calculatenettobrutto(1);">

And here is the corresponding JavaScript code:

function Calculatenettobrutto(n) {
  var Feldnummer = n;
  var nettowert, bruttowert;
  var nettosumme, bruttosumme, neuenettosumme, neuebruttosumme;
  var Wertfuer = 'Mehrwertsteuersatz';
  
  // Retrieving Mehrwertsteuer data
  var dataString = 'Name=' + Wertfuer;
  var thisObject = this;
  this.wert = $.ajax({
    type: "POST",
    url: "ajax_get_Einstellungen.php",
    data: dataString,
    cache: false,
    success: function(wert) {
      nettowert = document.getElementById('Netto' + Feldnummer).value;
      bruttowert = parseFloat(nettowert) * wert;
      document.getElementById('Brutto' + Feldnummer).value = parseFloat(bruttowert);
      return wert;
    }
  });

  var nettosumme = 0, bruttosumme = 0, x = 1;
  
  while (x < 30) {
    var Feldname = 'Netto' + x;
    
    if (document.getElementById('Netto' + x)) {
      var nettowert = document.getElementById('Netto' + x).value;
      
      if (nettowert) {
        nettosumme = parseFloat(nettosumme) + parseFloat(document.getElementById('Netto' + x).value);
        
        // The following line is crucial for correct calculations, even though it triggers an alert
        alert(nettosumme);
        
        bruttosumme = parseFloat(bruttosumme) + parseFloat(document.getElementById('Brutto' + x).value);
      }
    }
    
    x++;
  }
  
  document.getElementById('Nettosumme').value = parseFloat(nettosumme);
  document.getElementById('Bruttosumme').value = parseFloat(bruttosumme);
}

How can we ensure the function works properly even without the alert() line?

Answer №1

One issue you may be facing is related to an asynchronous ajax request being executed in your code:

<input type="text" onblur="Calculatenettobrutto(1)" />

When the user leaves the input field, Calculatenettobrutto function is triggered. This function then performs the following calculations:

var Feldnummer = 1;
this.wert=$.ajax({
   ...
   success: function(wert) {
      ...
      nettowert = document.getElementById('Netto'+Feldnummer).value;
      bruttowert = parseFloat(nettowert) * wert;
      document.getElementById('Brutto'+Feldnummer).value=parseFloat(bruttowert);
   }
});

//alert("Wait a little");
document.getElementById('Brutto'+Feldnummer).value <-- BANG

The issue arises because the code after the ajax() call is executed immediately, while the function defined within ajax() is called only upon receiving a response from the server. As a result, you are attempting to retrieve a value before it has been set.

During the alert window display, the script is paused, allowing the ajax call to return and update the "Brutto..." value as planned. Once the alert is closed, the remaining code is executed with the updated value now present.

A straightforward solution would be to relocate your sum calculation logic inside the "success" function of the ajax call.

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

What is the best way to save a jQuery or JavaScript variable into a JSON file?

Is there a way to save a jquery variable in a json file? I have the following: var image='/test/test.png'; I am obtaining this path through file upload: <input type="file" name="imageurl" value="imagefile"></input> Therefore, I ne ...

Exception encountered for Internet Explorer when attempting to launch from WebDriver: 405 Method Not Allowed

After trying to launch IE from Webdriver and clicking on save, I encountered a "405 Method not allowed" exception. However, when I manually launched IE and clicked on save, it worked fine. I'm perplexed by this issue. Any ideas as to why it might be ...

Avoiding unlimited re-renders when using useEffect() in React - Tips and Strategies

As a new developer, I recently built a chat application using socket io. In my code, I have the useEffect hook set to only change when the socket changes. However, I also have setMessage within the body of useEffect(), with socket as a dependency. Unfortun ...

Tips for displaying only a list of folders in elfinder, a jquery file management plugin

Currently, I am working on enhancing the features of a file manager plugin that allows users to manage their folders effectively. One key functionality of the plugin is the ability for users to share specific folders with others. However, if a folder has n ...

Tips for creating a zoomable drawing

I have been working on this javascript and html code but need some assistance in making the rectangle zoomable using mousewheel. Could someone provide guidance? var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); var width ...

Enhance Data3 Sankey to disperse data efficiently

There are a few instances where the D3 Sankey spread feature is showcased here. However, it seems that this specific function is not included in the official D3 Sankey plugin. Is there anyone who can assist me in obtaining the code for the Spread function ...

What is the best way to convert my Chatbot component into a <script> tag for seamless integration into any website using React.js?

I have successfully integrated a Chatbot component into my Next.js application. https://i.stack.imgur.com/BxgWV.png Now, I want to make this component available for anyone to use on their own website by simply adding a tag. My initial approach was to cre ...

Understanding the functionality of scope in AngularJS is essential for mastering the framework

Why does this code work? app.controller("ctrl", function($scope){ $scope.From = "Santa"; $scope.To = "Claus"; }); And why doesn't this one work? app.controller("ctrl", function(scope){ scope.From = "Santa"; scope.To = "Claus"; }); ...

What is the most efficient way to query through a Firestore database containing 5,000 users?

We are currently facing a challenge with our staffing application, which is built using vuejs and a firestore database containing over 5,000 users. Our primary issue lies in the need for a more efficient layout that allows admins to search for users within ...

JavaScript - splitting numbers into multiple parts

Need help with a JavaScript question regarding numbers like 2,5 or 2.5 I attempted to perform a multi-split operation using the following code: '2.5'.split(/,|./) However, it resulted in an incorrect output: ["", "", "", ""] ...

The functionality of angular-ui's ui-utils and ui-scroll module is currently nonfunctional in version 0.1.0

I have been trying to implement the features from this Angular UI library: http://angular-ui.github.io/ui-utils/, particularly focusing on this aspect: https://github.com/angular-ui/ui-utils/blob/master/modules/scroll/README.md Unfortunately, despite my e ...

Is there a way in Reactjs Material UI 5 (MUI5) to unselect only the star that was clicked, without affecting the rest of the stars in the

For instance: I selected the 3rd star on the rating component, but when I click on it again, all the previous stars disappear and it shows 0 stars. How can I make it so that if I click on the 3rd star a second time, only the 3rd star is removed, leaving ...

Is Same Origin Policy only enforced in incognito mode while utilizing Ajax?

When I attempt to use ajax to communicate with my server from a device, I encounter an issue. If I access the website in incognito mode, the service fails to work and logs the error message: Cross-Origin Request Blocked: The Same Origin Policy disallows ...

Reactjs: Prop Type Error - Issue with retrieving the values from props during data submission

Currently, I am developing a social app where users can post screams, like posts, and add comments. The issue I'm encountering is that I am not receiving the props value when posting a new scream initially, but after refreshing the page, everything wo ...

How can I place an Object in front of an Array in JavaScript?

Currently, I am working on an Angular project where I need to modify a JSON array in order to display it as a tree structure. To achieve this, the objects in the array must be nested within another object. Desired format / output: this.nodes = [ { id ...

Basic HTML Audio Player Featuring Several Customizable Variables

I have a unique API that manages music playback. Instead of playing audio in the browser, it is done through a Discord bot. Achievement Goal https://i.stack.imgur.com/w3WUJ.png Parameters: current: indicates the current position of the track (e.g. 2:3 ...

Tips for setting up a scheduled event on your Discord server using Node.js

Hello fellow programmers! Recently, I've been working on a Discord bot using discordjs sdk. I'm trying to implement a feature where the bot creates an event every week. I went through the discordjs guide and checked the discord api documentati ...

When using form.serialize() in Django forms, an empty object is being sent

Upon clicking the button, my AJAX request is sending an empty object Object { } instead of form data. The form on my page consists of checkboxes and its HTML structure is as follows: <form method="post" action="" data-id="filter-form"> //Included ...

Steer clear of duplicating patterns in vue templates

I have a significant issue with a component that needs to be repeated multiple times in the parent template due to the usage of v-if. The component code is as follows: <SelectCard v-for="(channel, index) in category.visibleChannels" :key="index + & ...

Controlling the angular bootstrap modal form with ease

I am having trouble accessing the form in the modal controller (Plunkr). The variable myForm doesn't seem to be accessible. How can I make the alert call work correctly: angular.module('plunker', ['ui.bootstrap']); var ModalDemoCt ...