Guide on calculating the total sum of numbers from multiple selected elements based on class within a div that has a designated id

https://i.sstatic.net/uyjPk.pngI'm currently working on a task that involves summing up the number of listeners from various servers. These values are stored within a div with the id="channel1", and each number of listeners is located in a span element with the class stats. My goal is to collect all these values with the class 'stats' inside the div with the id 'channel1'.

Here is the HTML and jQuery code snippet:

<div class="panel-body" id="channel1">
                 <div id="kanali1-a">
                    <h4>Server 1*</h4>
                    <span> IP: 85.93.88.146 Port: 8000</span>
                    Currently Listening: <span class="stats badge"></span><br>
                    <span>This is the main server where the transmission takes place.</span> 
                 </div>

                 <div id="kanali1-b">
                    <h4>Server 2</h4>
                    <span> IP: 85.93.88.146 Port: 8004</span>
                    Currently Listening: <span class="stats badge">10</span><br>
                    <span></span> 
                 </div>

               (Rest of the server details skipped for brevity)
              
               </div>

jQuery Code:

var statsCh1 = $('#channel1 .stats').text();
   var resCh1 = 0;

    for (var i=0; i<statsCh1.length; i++){
       resCh1 += statsCh1[i] << 0;
       //console.log(statsCh1[i]);
    }

   $('#kanal1Total').text(resCh1);

Answer №1

Perhaps you could try this approach:

let total = 0;
$('.stats').each(function () {
    total += (+ $(this).text());
});
$('#totalValue').text(total);

Answer №2

When you call $('#channel1 .stats').text(); on multiple elements, it will simply concatenate a list of strings together resulting in something like "01010101010".

To handle this correctly, you should iterate over each element individually. Here's a way to do this using the map and reduce functions:

// Iterate over each .stats element...
var values = $('#channel1 .stats').map(function() {
  // Ensure that the text is parsed as a Number...
  return parseInt($(this).text(), 10) || 0;
}).get(); // Converts the elements to a native array
// Now sum up the values obtained above
var sum = values.reduce(function(prev, curr) {
    return prev + curr;
}, 0);
console.log(sum);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="panel-body" id="channel1">
    <div id="kanali1-a">
        <h4>Server 1*</h4>
        <span> IP: 85.93.88.146 Port: 8000</span> Listening: <span class="stats badge"></span>
        <br>
        <span>This is the main server for broadcasting</span>
    </div>

    <div id="kanali1-b">
        <h4>Server 2</h4>
        <span> IP: 85.93.88.146 Port: 8004</span> Listening: <span class="stats badge">10</span>
        <br>
        <span></span>
    </div>

    <div id="kanali1-c">
        <h4>Server 3</h4>
        <span> IP: 85.93.88.146 Port: 8006</span> Listening: <span class="stats badge">10</span>
        <br>
        <span></span>
    </div>

    <div id="kanali1-d">
        <h4>Server 4</h4>
        <span> IP: radio-pendimi.com (all-inkl) Port: 8000</span> Listening: <span class="stats badge">10</span>
        <br>
        <span></span>
    </div>

    <div id="kanali1-e">
        <h4>Server 5</h4>
        <span> IP: 217.172.180.29 Port: 8000</span> Listening: <span class="stats badge">10</span>
        <br>
        <span></span>
    </div>

    <div id="kanali1-f">
        <h4>Server 6</h4>
        <span> IP: 217.172.180.29 Port: 8004</span> Listening: <span class="stats badge">10</span>
        <br>
        <span></span>
    </div>
</div>

Answer №3

Your code has a problem with

var statsCh1 = $('#channel1 .stats').text();
as it only retrieves the text from the first element in the jQuery collection, not all elements. This results in looping over a string instead of individual elements.

To correctly loop through the collection and read text from each element, you can use the 'each' method for a simple iteration:

var total = 0;
$("#channel1 .stats").map(function(){
    total += parseInt( $(this).text() ) || 0;
});
console.log(total);

Alternatively, you can utilize the 'map' and 'reduce' functions for a more sophisticated approach - though it involves additional looping:

var total = $("#channel1 .stats").map(function(){
   return parseInt($(this).text()) || 0;  
}).get()  
.reduce(  
    function (p, c) { return p + c;}, 0  
);
console.log(total);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="panel-body" id="channel1">
  <div id="kanali1-a">
    <h4>Serveri 1*</h4>
    <span> IP: 85.93.88.146 Porta: 8000</span>
    Duke degjuar: <span class="stats badge"></span>
    <br>
    <span>Ky eshte serveri kryesor ku behet transmetimi</span> 
  </div>

  <div id="kanali1-b">
    <h4>Serveri 2</h4>
    <span> IP: 85.93.88.146 Porta: 8004</span>
    Duke degjuar: <span class="stats badge">10</span>
    <br>
    <span></span> 
  </div>

  <div id="kanali1-c">
    <h4>Serveri 3</h4>
    <span> IP: 85.93.88.146 Porta: 8006</span>
    Duke degjuar: <span class="stats badge">10</span>
    <br>
    <span></span> 
  </div>

  <div id="kanali1-d">
    <h4>Serveri 4</h4>
    <span> IP: radio-pendimi.com (all-inkl) Porta: 8000</span>
    Duke degjuar: <span class="stats badge">10</span>
    <br>
    <span></span> 
  </div>

  <div id="kanali1-e">
    <h4>Serveri 5</h4>
    <span> IP: 217.172.180.29 Porta: 8000</span>
    Duke degjuar: <span class="stats badge">10</span>
    <br>
    <span></span> 
  </div>

  <div id="kanali1-f">
    <h4>Serveri 6</h4>
    <span> IP: 217.172.180.29 Porta: 8004</span>
    Duke degjuar: <span class="stats badge">10</span>
    <br>
    <span></span> 
  </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

I'm having trouble retrieving data from a nested object in React Native for iOS

Currently, I am diving into learning React Native specifically for iOS development. One issue that I am encountering is the inability to access information within an object, specifically a link to an image. Inside the renderRow function for listView in R ...

What are the best techniques for effectively employing jQuery Deferred/promise in automatically invoked functions like .ajax()'s beforeSend()?

In my project, I am customizing jQuery's ajaxPrefilter to enhance the functionality of AJAX requests. Specifically, I am adding header data to the XHR request using setRequestHeader() within the beforeSend() method. The challenge I am facing is that b ...

"Troubleshooting: Why is my AngularJS ng-click not triggering the function

My custom directive fetches a navigation block from a webservice call. I am attempting to click on a navigation link that has an "ng-click" attribute set, which should call the specified function. However, the function is not being executed. Below is my r ...

Usage of double quotation marks in jquery formbuilder is not permitted

I am currently utilizing jQuery Formbuilder to create forms and saving the JSON data to a database. When editing the formbuilder, I retrieve the data as shown below: var options = { formData: '<?php echo str_replace("'","\'",$fo ...

Unable to establish a WebSocket connection in Django channels due to connectivity issues

As I dive into creating a socket-based application using Django-Channels, I've encountered an issue with connecting to the WebSocket. To demonstrate this problem, I set up a test project. The error message displayed in the JS Console: WebSocket con ...

Convert the checkbox array into a CSV format

Is there a way to utilize jQuery to convert the checked checkbox values with name=ap[] into comma separated values for easy parsing as a query string? I found that using .serialize() makes the string too complex. Any alternative suggestions on how to ach ...

Troubleshooting: jQuery's clone( true ) function fails to function properly with dynamic

Consider this scenario: $.fn.foo = function() { var $input = $('<input type="text"/>'); var $button_one = $('<button>One</button>'); var $button_two = $('<button>Two</button>'); ...

What is the best way to find the most commonly used category for a product in a MongoDB collection?

I've been diving into MongoDB and encountered a challenge with my current task. I'm trying to figure out how to determine the most frequently used category in a collection. According to this JSON, the most used category is CIES. My goal is to dis ...

Converting HTML to PDF: Transform your web content into

I have a couple of tasks that need to be completed: Firstly, I need to create a functionality where clicking a button will convert an HTML5 page into a .PDF file. Secondly, I am looking to generate another page with a table (Grid) containing data. The gr ...

Searching for text on a webpage without an identifier using C#

How can I locate specific text on a webpage that is not designated with a specific ID or tag, but is simply plain text generated by an external source that I cannot control? I am using WatiN for automated testing and I need to find a way to click a button ...

What is the best way to create a box-shadow with an inset effect and a touch of

Looking to dive into the world of css3 design and wondering how to achieve a box-shadow inset with a touch of transparency. Check out the example in this fiddle link: http://jsfiddle.net/TeGkt/4/ Any ideas on how to replicate this effect without relying ...

Newly added rows to the table after filtering remain visible

I am currently using the DataTable API and jQuery to create a table by fetching rows from the server. However, I encounter an issue when I click a button to load additional rows and append them to the end of the table. The problem arises when I try to hide ...

How can I access a list in the code behind of an ASPX file and iterate through it using JavaScript in a foreach

Here is the code snippet in my aspx.cs file: public partial class BarChart { public class LabelsDetail { public string LabelId { get;set; } public string LabelDesc { get; set; } } public List<LabelsDetail> LabelsDeta ...

What is the best way to establish a connection between two applications using React and Node

Currently, I am facing a challenge with integrating two separate applications. One is a login/registration form written in Node.js, Express.js, React.js, and MySQL. The file structure looks like this: https://i.sstatic.net/th6Ej.png The other application ...

Creating a conditional statement within an array.map loop in Next.js

User Interface after Processing After retrieving this dataset const array = [1,2,3,4,5,6,7,8] I need to determine if the index of the array is a multiple of 5. If the loop is on index 0, 5, 10 and so on, it should display this HTML <div class="s ...

Stopping setinterval on click can be achieved by using the clearInterval function in

I've encountered an issue while using a slideshow on my website. The plugin I'm using does not have an autoplay feature, so I had to implement it using setinterval in my code. Below is the code I used: var myInterval, startInt = function(){ ...

Coloring the table upon selecting a checkbox using AJAX, JavaScript, and JSP

How can I adjust the color of the entire table (every row of the table)? Currently, I can only change the color of the first row of my table. Here is my color function in JSP: function changeColor(rowID){ var row = document.getElementById(rowID); ...

Exploring the use of $ in the outcome of a json for jQuery autocomplete functionality

Trying to implement auto complete functionality. Here is the URL I need to read JSON from: http://openscan.addi.dk/2.0/?action=openScan&field=phrase.title&lower=hest&limit=10&outputType=json After receiving the result, I'm attempting ...

CORS response header is not included

Is it the company's responsibility () to rectify one of their endpoints or is it an issue with my code? I have tested all other endpoints () using the same code below and they all function correctly, except for the specific one in question. The erro ...

JavaScript function to add or subtract

I need to include additional inputs for "+ and -" 60mm and 120mm in my function. How can I achieve this without turning all of them into separate functions? <template> <card class="card"> <h2>Measurement</h2> <form&g ...