Unable to automatically calculate JavaScript when the number is not manually typed into the dropdown menu

Calculating A and B vertically from a dropdown combo box has been a challenge. Here is a sample data set:


            Data
               A      B  
----------------------------
    1      |   1   |  0
    2      |   0   |  1
    3      |   0   |  1
----------------------------
    Result |   1   |  2  (calculation still not functioning as expected)

The goal is to calculate A and B vertically from the dropdown combo box selections and display the results, but unfortunately, the calculation is still not working properly.

Code :

HTML

<select id="k1" class="tes" name="kelayakan1" size="1">
  <option value="">-- Choose One --</option>
  <option value="1">Eligible</option>
  <option value="0">Not Eligible</option>
</select>
<br>
... (more HTML code here)
<br> I want to calculate A and B vertically ..

Javascript

   $(document).ready(function() {
     //Iterate through each Textbox and add keyup event handler
     $(".tes").each(function() {
       $(this).change(function() {
         //JavaScript code for calculating A vertically goes here
       });
     });

     //Additional JavaScript code for calculating B vertically goes here
     
     //More JavaScript code for handling calculations


 jml = total;
 $("#hasil1").val(jml);


   });

To see this in action, check out the JSFIDDLE example: https://jsfiddle.net/taraym/zo5j7wn9/1/

Answer №1

Tested and verified code:

function sumCalculator(){

//Calculate Total Sum For A
var A = [];  var totalA = 0;
$('#tbl_data tr:not(:has(th))').not(':last').each(function(){   
   A.push($(this).find("td:eq(1)").text().trim());
})

for (i = 0; i < A.length; ++i) {      
         if (A[i]!='') {totalA += parseInt(A[i]);}
}
$('#tbl_data tr:last').find('td:eq(1)').text(totalA);

//Calculate Total Sum For B
var B = []; var totalB = 0;
$('#tbl_data tr:not(:has(th))').not(':last').each(function(){   
   B.push($(this).find("td:eq(2)").text().trim());
})

for (i = 0; i < B.length; ++i) {      
         if (B[i]!='') {totalB += parseInt(B[i]);}
}
$('#tbl_data tr:last').find('td:eq(2)').text(totalB);

}

Insert sumCalculator(); after every dropdown change action.

Verified Demo

Expecting this to be beneficial!

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

Utilizing Emotion CSS to incorporate images into buttons

I'm trying to add some style to two buttons, Up and Down, by using emotion CSS but I'm having trouble. Currently, I typically style my elements within a function. Is there a way for me to accomplish this with emotion CSS? I checked out but still ...

The collapsible menu is not expanding properly after a click event due to the small size of

My website has a menu placed in the header with a background color. When resizing the page (max width 1044 px), it switches to a mobile menu, but the div holding the menu and anchors is too small compared to the header. Is there a solution to this issue? ...

I am finding the event naming conventions in Vue 3 to be quite perplex

In the parent component, there is a child component: <upsetting-moment-step :this-step-number="1" :current-step-number="currentStepNumber" @showNextStep="showNextStep" ></upsetting-moment-step> The par ...

I am looking to transmit information from flask to React and dynamically generate HTML content based on it

index.py @app.route('/visuals', methods=["GET", "POST"]) def visuals(): global visclass return render_template('visframe.html', images=visclass.get_visuals()) visframe.html <div id='gallery'></div> { ...

When making a JQuery - Ajax get request, I did not receive the "extracts" or "exintro" (summary) property in the response

Lately, I've been working on a small web application that displays search results from Wikipedia on the webpage after entering a search term into a text field. This has been a project that I’ve dedicated a lot of time to. I have configured an ajax g ...

Is there a way to access the Express parameters within my React component?

Currently, I am in the process of developing a React application that utilizes Express as its back-end infrastructure My express route is configured as follows app.get('/manage/:id', (req, res) => { // redirect to react application }); ...

Troubleshooting: Why is my Local Image not displaying in ReactJS

I am facing an issue with displaying images in my React application using an array of image paths. Below is the code snippet I have written: import React, { Component } from 'react'; class ItemsList extends Component { constructor() { ...

Tips for automatically displaying the first option as selected in an HTML Select dropdown

I have an HTML select element where I want the option chosen by the user to not be displayed in the box. Instead, I would like the box to always show the first option, regardless of what the user selects from the dropdown menu. Below is my CSS code for sty ...

Issue with jQuery slider failing to slide in some situations

Check out the code on jsfiddle It seems like there might be an issue with the slide function: slide: function( event, ui ) { var input = this.next(':input'); input.val(input.attr('alt') + ui.value); } ...

Resolving the 'unexpected token u' error in ASP.NET MVC

Having some trouble implementing autocomplete in my asp.net mvc 4 project. I keep getting an error: unexpected token u. From what I understand, it means there's an unidentified object but I'm not sure how to fix it. Any suggestions? <link rel ...

When attempting to upload a file from IOS10.3.1, the server received the correct file size but retrieved incorrect data, all of which appeared as

I'm facing issues with correctly uploading files. Our iOS and Android app allow users to select a local image file and upload it to our Nginx server. Issue Summary: Approximately 5% of the total upload requests result in broken image files on the se ...

Is there a problem with the refresh method in Javascript not functioning properly in Edge browser?

As I embark on my current project, a challenge presents itself: I require the page to automatically refresh once the music has concluded. Surprisingly, this code performed flawlessly on Chrome and Firefox. setTimeout(location.reload.bind(location), 206000 ...

An effective method for modifying the active class on an li element in jQuery and ensuring that the user is directed to the desired page upon clicking the li element

I am facing an issue with my script tag. When I click on the links test.php or test2.php, the active class changes from index.php to the respective file but I am not redirected to the clicked page. I have tried solutions from various sources but none of th ...

What is the best way to connect input values with ngFor and ngModel?

I am facing an issue with binding input values to a component in Angular. I have used ngFor on multiple inputs, but the input fields are not showing up, so I am unable to push the data to subQuestionsAnswertext. Here is the code snippet from app.component ...

Creating dynamic and engaging videos using Angular with the ability to make multiple requests

I am facing an issue while working with videos in Angular. I am fetching the video URLs from an API to embed them in my application using the sanitazer.bypassSecurityTrustResourceUrl function provided by Angular. The videos are being displayed correctly wi ...

Issue: MaxDate and minDate properties are not functioning correctly with the MultiDate feature on the Datepicker

I am working on creating a custom date picker that allows users to select multiple random dates within a specified range. However, I have encountered an issue where the multidate feature is not working when using minDate and maxDate parameters. $('.da ...

Need help with creating a new instance in AngularJS? Unfortunately, the save method in CRUD is not getting the job done

Whenever I attempt to create a new task, nothing seems to happen and no request is being sent. What could be causing this issue? How can I go about troubleshooting it? Take a look at how it appears here Check out the $scope.add function below: var app ...

Using Ajax to make a request on the same page but specifically within a column

I'm currently experimenting with AJAX to display live CSV data on my website. Right now, the AJAX script triggers on button click, but what I really want is for the data to be shown in a grid view without requiring a refresh or clicking a button. Howe ...

When trying to upload a file through input using WebDriver, the process gets stuck once the sendKeys

WebElement uploadInput = browser.findElementByXPath("[correct_identifier]"); uploadInput.sendKeys(elementPath); The script successfully initiates the file upload process, however, the custom JavaScript loading screen persists and fails to disappear as exp ...

Trouble assigning the 'data' attribute to the 'Object' tag using jQuery. [Limited to IE8]

I have encountered a problem when creating an object element dynamically in jQuery to display some content. The code functions perfectly in all browsers except for IE8. Here is the code snippet: j$(document).ready(function(){ j$('.ob ...