My JavaScript computations are not functioning as expected

Below is the Javascript code I am using:

$(".myCorOpt").change(function () {
    var $corporateA = $("#corporateA").val();
    var $corporateB = $("#corporateB").val();
    var $corporateE = $("#corporateE").val();

    var $corElevators = Math.ceil($corporateE * ($corporateA + + $corporateB) / 1000);
    var $corColumns = Math.ceil(($corporateA + + $corporateB) / 20);
    var $elevatorsPerColumnsCor = Math.ceil($corElevators / $corColumns);
    var $corTotalElevators = $elevatorsPerColumnsCor * $corColumns;
})

Given that $corporateA = 89, $corporateB = 6, and $corporateE = 240. If I manually perform the calculations, I expect the following results:

Math.ceil(240(89+6)/1000) = 23
Math.ceil((89+6)/20) = 5
Math.ceil(23/5)=5
$corTotalElevators = 5*5=25

However, when I input these values into my quote form on the website, the final result shows as 225 instead of 25. Can anyone help me figure out what went wrong?

Answer №1

To convert the input field value into an integer, use the following code:

parseInt($('#corporateA').val(), 10) // 89 (integer)

A helpful tip is to refrain from using the dollar sign with non-jQuery objects.

Correct Method

let $corporateA = $('#corporateA'); // Storing a jQuery DOM object
let valA = parseInt($corporateA.val(), 10);

Creating a jQuery Plugin

You can create your own jQuery plugin for a more convenient and concise method.

(function($) {
  $.fn.intVal = function(radix) {
    return parseInt(this.val(), radix || 10);
  };
})(jQuery);

let corporateA = $('#corporate-a').intVal();
let corporateB = $('#corporate-b').intVal();
let corporateE = $('#corporate-e').intVal();

Demonstration in Action

In HTML coding standards, it's recommended to use kebab-case or snake-case for element IDs and classes instead of lower camel-case.

$('.my-cor-opt').change(function(e) {
  let corporateA = parseInt($('#corporate-a').val(), 10);
  let corporateB = parseInt($('#corporate-b').val(), 10);
  let corporateE = parseInt($('#corporate-e').val(), 10);
  
  let corElevators = Math.ceil(corporateE * (corporateA + corporateB) / 1000);
  let corColumns = Math.ceil((corporateA + corporateB) / 20);
  let elevatorsPerColumnsCor = Math.ceil(corElevators / corColumns);
  let corTotalElevators = elevatorsPerColumnsCor * corColumns;

  alert(corTotalElevators); // 25
});

$('.my-cor-opt').trigger('change');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="corporate-a" value="89" />
<input id="corporate-b" value="6" />
<input id="corporate-e" value="240" />
<select class="my-cor-opt"></select>

Answer №2

To convert the values of the input fields from strings to numbers, you have two main options available.

The first approach is to prepend a unary plus operator to each input field value. The second method involves using the parseInt function.

If you skip the conversion step and attempt arithmetic operations on string values, the binary plus operator will concatenate the strings instead of adding them together.

'1' + '2' + '3' // '123'
1 + 2 + 3 // 6
+'1' + +'2' + +'3' // 6
parseInt('1', 10) + parseInt('2', 10) + parseInt('3', 10) // 6

For more in-depth analysis, refer to this link: parseInt vs unary plus, when to use which?

Unary plus operator

"use strict";
console.clear();

$(".myCorOpt").change(function () {
  var $corporateA = +$("#corporateA").val();
  var $corporateB = +$("#corporateB").val();
  var $corporateE = +$("#corporateE").val();

  var $corElevators = Math.ceil(
    ($corporateE * ($corporateA + $corporateB)) / 1000
  );
  var $corColumns = Math.ceil(($corporateA + $corporateB) / 20);
  var $elevatorsPerColumnsCor = Math.ceil($corElevators / $corColumns);
  var $corTotalElevators = $elevatorsPerColumnsCor * $corColumns;

  $('#corElevators').val($corElevators);
  $('#corColumns').val($corColumns);
  $('#elevatorsPerColumnsCor').val($elevatorsPerColumnsCor);
  $('#corTotalElevators').val($corTotalElevators);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="myCorOpt">
  <table>
  <tr><td>Corporate A</td><td><input id="corporateA" placeholder="corporateA" value="89"></td></tr>
  <tr><td>Corporate B</td><td><input id="corporateB" placeholder="corporateB" value="6"></td></tr>
  <tr><td>Corporate E</td><td><input id="corporateE" placeholder="corporateE"></td></tr>
  <tr><td colspan="2"><hr></td></tr>
  <tr><td>Elevators</td><td><input id="corElevators"></td></tr>
  <tr><td>Columns</td><td><input id="corColumns"></td></tr>
  <tr><td>Elevators per Columns</td><td><input id="elevatorsPerColumnsCor"></td></tr>
  <tr><td>Total Elevators</td><td><input id="corTotalElevators"></td></tr>
</form>

parseInt

"use strict";
console.clear();

$(".myCorOpt").change(function () {
  var $corporateA = parseInt($("#corporateA").val(), 10);
  var $corporateB = parseInt($("#corporateB").val(), 10);
  var $corporateE = parseInt($("#corporateE").val(), 10);

  var $corElevators = Math.ceil(
    ($corporateE * ($corporateA + $corporateB)) / 1000
  );
  var $corColumns = Math.ceil(($corporateA + $corporateB) / 20);
  var $elevatorsPerColumnsCor = Math.ceil($corElevators / $corColumns);
  var $corTotalElevators = $elevatorsPerColumnsCor * $corColumns;

  $('#corElevators').val($corElevators);
  $('#corColumns').val($corColumns);
  $('#elevatorsPerColumnsCor').val($elevatorsPerColumnsCor);
  $('#corTotalElevators').val($corTotalElevators);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="myCorOpt">
  <table>
  <tr><td>Corporate A</td><td><input id="corporateA" placeholder="corporateA" value="89"></td></tr>
  <tr><td>Corporate B</td><td><input id="corporateB" placeholder="corporateB" value="6"></td></tr>
  <tr><td>Corporate E</td><td><input id="corporateE" placeholder="corporateE"></td></tr>
  <tr><td colspan="2"><hr></td></tr>
  <tr><td>Elevators</td><td><input id="corElevators"></td></tr>
  <tr><td>Columns</td><td><input id="corColumns"></td></tr>
  <tr><td>Elevators per Columns</td><td><input id="elevatorsPerColumnsCor"></td></tr>
  <tr><td>Total Elevators</td><td><input id="corTotalElevators"></td></tr>
</form>

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

Having trouble activating my Nav Toggle button on Bootstrap 4

My navbar toggle button isn't working and I'm not sure why. Could it be that I'm missing a class? Any help would be greatly appreciated as I've tried to find a solution on my own without success. Thanks <head> <meta charse ...

Setting up Socket.io results in numerous transport polling GET requests being initiated

I have set up an express.js server-side and followed the socket.io guide. However, I am facing issues with the socket connection not being successful, and there seems to be a high number of unexpected GET requests like this: https://i.stack.imgur.com/GDGg ...

How can I rectify the varying vulnerabilities that arise from npm installation?

After running npm audit, I encountered an error related to Uncontrolled Resource Consumption in firebase. Is there a solution available? The issue can be fixed using `npm audit fix --force`. This will install <a href="/cdn-cgi/l/email-protection" clas ...

The sidebar.querySelector method is not working as expected

Attempting to assign an 'active' class to the clicked 'nav-link' element in order for it to stay active on the next page the user navigates to. Encountering an issue with sidebar.getElementsByClassName is not a function showing up in t ...

implementing a webpage enhancement that enables loading content asynchronously

I find myself puzzled. Lately, I've delved into learning Spring MVC through the development of a web application designed to display live sports scores in real-time. The core functionalities are already in place, but I'm unsure about how to creat ...

"Enhance your web application with dynamic drop-down selection using Spring, Ajax

In my JSP file, I have a script that populates the list of states based on the selected country. The script fetches data from the controller and is supposed to display the list of states. However, after calling the controller method, the alert "received da ...

What is the best way to confirm if a Json response is empty or not?

{"PatientPastMedicalHistoryGetResult":{"PastMedicalHistory":[]}} The PastMedicalHistory object does not contain any values. How can I verify if it is empty? ...

Sending an Ajax request using a dropdown menu

I'm having trouble retrieving a value from my database when a select option is chosen. The select options are generated dynamically from the same database. As a beginner in AJAX requests, I am struggling to figure out why I am only getting a blank re ...

Preventing window resize from affecting print screen content in Angular 8

I'm struggling with a print button feature in my Angular 8 project. When the window is resized, the content within the print window also resizes, which is not the behavior I want. I've tried a couple of solutions, but nothing has worked so far: 1 ...

Display a specific element only if another element exceeds a specified height

A snippet of HTML code is given below: <span class="day-number">{{day-number}}</span> <div class="event-box"> <div class="event-container"> </div> <div class="more-events">more ...</div> </div> The .e ...

How can I receive user input in JavaScript while incorporating three.js?

I am currently exploring the functionalities of this three.js example () and I am interested in enabling users to input specified X, Y, and Z positions for boxes dynamically. Initially, I considered utilizing a JavaScript prompt like below: var boxes = p ...

Errors are caused when attempting to install third-party JS plugins using npm within a foundation project

I am currently exploring projects involving NodeJS and npm. While experimenting with foundation CLI in Foundation 6.4, I decided to install a 3rd Party JS plugin called chart.js from https://www.chartjs.org/ Following their documentation, I ran the comman ...

How can we retrieve the isolated directive scope variable in the link function of AngularJS?

Check out the code snippet provided below. directive: app.directive("filterTree", function() { return { restrict: "AE", controller: function($scope, $http){ $scope.treeNodes = []; var filterItemsUrl = "/api/v1/ ...

Spontaneously generating visuals that lead an unpredictable existence

Every 0-2 seconds, I generate a unique image and place it randomly within a designated area. setTimeout("addImage()", Math.floor((Math.random() * 2000) + 1)); To maintain order, I want these images to vanish after being visible for an interval o ...

Experiencing issue with React TS when creating a Progress Bar; despite declaring types in the interface, an error is being thrown indicating implicit type 'any'

Attempting to replicate the design and functionality of this Codepen using React Typescript has been a challenge. I made adjustments like changing class to className and transferring the CSS styles to my App.css file. Even after defining types in my interf ...

How do I search for and display a collection associated with another in Mongoose?

I am currently working on a task to locate and display all questions related to the "Question Collection" that are associated with all the surveys created by a specific user in the "Surveys Collection". Although I have successfully found questions for a pa ...

Tips for making a Google Map API Element fit perfectly in a Bootstrap column below a heading

I've spent countless hours trying to solve this on my own, scouring the internet for answers with no luck. I'm hoping someone here can spare a few moments to help me out. Much appreciated! I'm attempting to make the Google Maps API element ...

An uncaught exception has occurred: An error was encountered indicating that the specified path is not valid for either posix or windows systems, and it appears that there is no 'join' method defined in the

I am currently working with nextjs version 13.5.6 using the app router and app directory. This issue arises during the compilation of the route app/(home)/page.js. The folder and file structure within the app folder is as follows: app/ -(home)/page.js -ser ...

What is the best way to change the date format in the GET API response for all objects

Recently started working with Angular, I'm receiving object data from an API call. data= [ { "Id": 4, "IssueDate": "2021-01-25T15:17:00.85", "ExpiryDate": "2021-01-25T15:25:40.263" ...

Selecting from dropdown menu showing limited options extracted from XML data

Need help with populating a combo box named combo_assembly using Ajax. The function to achieve this is: function populate_combo_assembly(xmlindata) { var xmldata = xmlindata.getElementsByTagName('Assemblies'); if(xmldata.length <= 0) { ...