Calculate the sum of input values in a JavaScript function with the same class

Can anyone help me figure out how to sum the values of input fields with the same class? I've attempted the code below but it doesn't seem to be working. Any ideas on what I'm doing wrong?

<table id="tableID">
<tr>

<td>   <input name="name" class="compulsory1" type="text" value="1" />  </td>
<td>   <input name="name1" class="compulsory1" type="text" value="2" />  </td>
<td>   <input name="name2" class="compulsory1" type="text" value="3" />  </td>

<td>
<script type="text/javascript">
var tdsCompulsory = document.getElementsByClassName('compulsory1')[0].value;
var cData = [];
sum = 0;
for(var i in tdsCompulsory){
    if(typeof tdsCompulsory[i].textContent != 'undefined')
    cData.push(tdsCompulsory[i].textContent);
}
console.log(cData);

for(var i in cData){
    sum +=parseInt(cData[i]);
}
alert (sum);
</script>

</td>

</tr>
</table>

Answer №1

Give this a shot: try using querySelectorAll. By doing so, you can retrieve all elements in the document that have the class "compulsory1":

window.onload = function(){
var x = document.querySelectorAll(".compulsory1");
var total = 0;
for(var i=0;i<x.length;i++)
{
total+=Number(x[i].value);
}
console.log(total);
}
  <input name="name" class="compulsory1" type="text" value="1" /> 
  <input name="name1" class="compulsory1" type="text" value="2" /> 
  <input name="name2" class="compulsory1" type="text" value="3" /> 

Answer №2

It appears that tdsCompulsory in your solution is not an array, but rather a number corresponding to the first element(input).

var tdsCompulsory = document.getElementsByClassName('compulsory1');
var len = tdsCompulsory.length;
var cData = [];
sum = 0;
for(var i = 0; i < len; i++){
    cData.push(tdsCompulsory[i].value);
    sum += +tdsCompulsory[i].value 
}
alert (sum);
<table id="tableID">
<tr>

<td>   <input name="name" class="compulsory1" type="text" value="1" />  </td>
<td>   <input name="name1" class="compulsory1" type="text" value="2" />  </td>
<td>   <input name="name2" class="compulsory1" type="text" value="3" />  </td>

<td>

.

Answer №3

Here

var tdsCompulsory = document.getElementsByClassName('compulsory1')[0].value;

Your variable tdsCompulsory contains a single element, as you are accessing the element at index [0].

To modify your code:

var tdsCompulsory = document.getElementsByClassName('compulsory1');

for(var i = 0; i < tdsCompulsory.length; i++){
    if(typeof tdsCompulsory[i].value != undefined){
       cData.push(tdsCompulsory[i].textContent);
    }
}

console.log(cData);

for(var i in cData){
    sum += parseInt(cData[i]);
}
alert(sum);

Alternatively, you can use the forEach method:

[].foreach.apply(tdsCompulsory, (el) => {
   if(typeof tdsCompulsory[i].value != undefined){
        cData.push(tdsCompulsory[i].value);
     }
});

Answer №4

If you want to use jQuery to achieve the same output, you can follow the code snippet below:


  <table id="tableID">
    <tr>
      <td><input name="name" class="compulsory1" type="text" value="1" /></td>
      <td><input name="name1" class="compulsory1" type="text" value="2" /></td>
      <td><input name="name2" class="compulsory1" type="text" value="3" /></td>
    </tr>
  </table>

  <input type="Button" value="Show Sum" onclick="sumAll()">

  <script> 
    function sumAll(){
        var values = $('.compulsory1');
        var sum = 0;
        for (var i =0; i<values.length; i++) {
          console.log(values[i]);
          sum += parseInt($(values[i]).val());
        }
        alert(sum);
     }
  </script>

Best regards, Ravi

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

Adjusting a Vue Slider with a changing value

Currently, I am utilizing the Vue Slider component from this source. My goal is to enhance the functionality of the slider by increasing it to the next index and beyond. The issue lies in the fact that the current implementation increments by 1, as the val ...

Refreshing select2 dropdown options dynamically with AJAX updates

I have a select dropdown for locations that is initialized using select2 on page load. I am looking to dynamically update the data in the dropdown at regular intervals using ajax calls. However, when I attempt to update the data in select2, the dropdown ...

Having trouble with flash messages in Node.js?

Could anyone shed some light on why the flash messages are not displaying properly in my situation? Here is how I'm attempting to utilize them: This snippet is from my app.js file: var express = require('express'); var app = express ...

Keep an eye out for classes that are added dynamically

Are there any event listeners available that can watch for and execute code when a class is dynamically added to an element? I'm working within a WordPress CMS and a plugin I am using adds classes dynamically. I want to be able to detect this and then ...

Link that updates periodically linked to an image

My goal is to have a URL change on a timer that is linked to an image. For example, after 10 seconds, I want the URL attached to the image to change without changing the actual image itself. I've been trying to figure out how to modify this code, but ...

JavaScript: Move the cursor to a specified position while updating the input value

In my application, I am aiming to create a user experience similar to Microsoft Excel / Google Sheets where there is an autocomplete dropdown for formulas and variables. Once the autocomplete has been validated, I want to have control over the cursor posit ...

Could anyone assist me in finding a way to exclude a particular "class" from being iterated over while utilizing ng-repeat in Angularjs?

Utilizing AngularJS within the framework of my Bootstrap carousel has presented a challenge. When I implement the directive ng-repeat="album in ActiveSinger.albums" to loop through my array, it continuously adds the class "active" to each div element. This ...

The transformation of elements within a C array may appear peculiar

I've encountered a strange issue with my code. Sometimes when I print arr[4], the value is 0, but other times it's 2. It's puzzling! #include <stdio.h> #include <string.h> int countBalls(int, int); void main() { int res; ...

Error: Google Chrome Extension must be used on the Dev Channel or a newer version

I am currently working on developing a Chrome extension for creating URL shortcuts. However, upon trying to add it to the browser, I encountered the following error: There were warnings during the installation of this extension: * 'app.lin ...

Commence the list from the lowest point

I am currently working with Ionic 2 and have a list of items: this.firelist = this.dataService.findMessages(this.chatItem).map(items => { this.updateReadMessages(items); return items.reverse(); }); These items are displayed in a list: <ion-con ...

react native is not updating the view even though the state has been changed

Upon opening my component, I am looking to retrieve Assets from a Media Folder (which is currently functional) and then pass them along to another component. However, the issue arises when launching the app for the first time, as the "listOfAssets" state a ...

Having trouble populating an OnsenUI list with AngularJS parse in Cordova

I have been working on retrieving a list of names from parse and adding them to an onsenui list. The parse query seems to be functioning correctly as I logged the results successfully, but for some reason, the list items are not appearing anywhere. Below ...

Acquire a structured list of the focus order within the DOM elements

It intrigues me how the DOM is constantly changing. I'm curious if there's an easy way to retrieve a sorted list of focusable elements within the DOM at any moment. This would encompass nodes with a specified tabindex value that isn't -1, as ...

Why is Validators.pattern not functioning in production when it works perfectly in my local development environment for Angular?

Why is Validators.pattern not working in the production environment but functioning fine in my local development setup? I implemented Validators.pattern and '*ngIf="email.errors.pattern"' for email validation on an existing form. Every ...

There was an issue with the v-on handler that threw an error: "Error: Reference.set failed because the first argument contains undefined."

I'm struggling to pinpoint where exactly the error occurs. Despite numerous attempts to log all the input data for the database, everything seems to have values... https://i.sstatic.net/TBk1L.png The goal is to store the current message in the datab ...

Executing a search and replace function using a delay within a foreach loop - the ultimate guide

Below is a snippet of code where I attempt to perform find and replace within an array by searching for keys and replacing them with corresponding values. However, the expected functionality does not work as intended, leading to multiple searches for &apos ...

Discover the art of extracting various words from a string in Java

I've encountered a challenge in extracting words of unknown length from a string, also of unknown length, that I'm parsing from a file. The words I need are always separated by "." and/or "&", enclosed within quotes. For example: ".Word.Chara ...

Error encountered while attempting to install material-ui v3.0.3 due to an unexpected termination of the JSON input

I'm currently in the process of installing the most recent stable version of material-ui(v3.03) by running: npm install @material-ui/core. However, I encountered an issue with npm ERR! Unexpected end of JSON input while parsing near '...-/brcast- ...

What could be the reason for my empty $routeProvider?

Question: I'm facing an issue with the $routeProvider in my code. Here's my configuration: $routeProvider .when('/language/:countryCode', routing) .when('/promotion/:promotionCode', routing) .otherwise ...

Determination of the winner in a tic tac toe game is not accurate using the if statement

I need some help with an issue I'm having with my code involving the "if statement". I am trying to complete my tic-tac-toe game by writing a function that determines the winner of the game. The problem arises when I try to compare the content of spec ...