An intuitive approach to adding a CheckBox control within a GridView using JavaScript and SPAN elements

Struggling to calculate the total quantity from the gridview for checked row checkboxes? Having trouble accessing the checkbox control in your JavaScript? Below is the code snippet you provided, but it's not returning anything.

    <table cellspacing="0" cellpadding="1" rules="all" border="1" id="grdView" style="background-color:#F2F4FF;width:100%;border-collapse:collapse;">
         <tr>
            <td align="center">
                            <span class="chkSelected" style="display:inline-block;border-style:None;"><input id="grdView_ctl02_chkSelect" type="checkbox" name="grdView$ctl02$chkSelect" /></span>
                            <input type="hidden" name="grdView$ctl02$hdDocId" id="grdView_ctl02_hdDocId" value="DO0002" />
                            <input type="hidden" name="grdView$ctl02$hdScope" id="grdView_ctl02_hdScope" value="Dlv" />
                            <input type="hidden" name="grdView$ctl02$hdDocType" id="grdView_ctl02_hdDocType" value="DO" />
                            <input type="hidden" name="grdView$ctl02$hdRefNo" id="grdView_ctl02_hdRefNo" />
                            <input type="hidden" name="grdView$ctl02$hdServiceType" id="grdView_ctl02_hdServiceType" />
                            <input type="hidden" name="grdView$ctl02$hdQty" id="grdView_ctl02_hdQty" />
                            <input type="hidden" name="grdView$ctl02$hdWeight" id="grdView_ctl02_hdWeight" />
                        </td>
        </tr>
    </table>

function calculateTotal()
    {        
        var sum = 0.00; 
        var itemsum = 0.00;        
        var gv = document.getElementById('grdView'); 

        for (var row = 1; row < gv.rows.length; row++) {          
            var cb = gv.rows[row].cells[0].childNodes[0].getElementsByTagName('input');
            if (cb.checked) {
                var quantity = gv.rows[row].cells[8].innerText;
                try {
                    sum += new Number(quantity);
                } catch (err) {
                    alert(quantity);
                }
            }
        } 
        alert(sum.toString()); 
        return false;
       
    }    

Answer №1

After spending a few days troubleshooting, I finally managed to get the correct output with the following code. I hope this will be helpful and save time for other beginner JavaScript developers (just like me :)). Keep coding!

function calculateTotal()
{
    var sum = 0.00;     
    var gv = document.getElementById('grdView'); 
    for (var row = 1; row < gv.rows.length; row++) {
        const collection = gv.rows[row].cells[0].children;
        var cb = collection[0].firstChild;           
        if (cb.checked) {
            var quantity = gv.rows[row].cells[8].innerText;
            try {
                sum += new Number(quantity);
            } catch (err) {
                //how to alert(quantity);
            }
        }
    } 
    var lbltotal= document.getElementById('lblTotalQty');
    lbltotal.innerHTML = sum.toString(); 
    return false;       
}  

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

The POST response I received was garbled and corrupted

Operating under the name DownloadZipFile, my service compiles data and constructs a Zip file for easy downloading. This particular service provides a response that contains the stream leading to the file. A Glimpse of the Service: [HttpPost] public Actio ...

Execute an xmlhttprequest and then redirect to a different URL

I'm a beginner when it comes to AJAX and JavaScript. My goal is to first show a confirmation box, then send an XMLHttpRequest if confirmed. After that, I want to redirect the user to a new page. Below is my current code: <script type="text/javascr ...

What is the best way to initiate the registration page through the @auth0/auth0-react library?

I've hit a roadblock in trying to automatically launch the sign-up (registration) page using @auth0/auth0-react. Previously, I would send mode which worked with auth0-js. So far, I have attempted the following without success: const { loginWithRedir ...

Steps for linking a page to a modal without embedding the page's content within the modal

Here is a snippet of code for a modal (from Twitter Bootstrap) that I am currently working with: <!-- Large Modal --> <button type="button" class="btn btn-primary" data-toggle="modal" data-target=".bs-example-modal-lg">Large Modal</button&g ...

Issue with swal() not triggering in Internet Explorer 11

Looking for some assistance here, I believe I might be missing a small detail. The _layout.cshtml file includes all the necessary scripts to ensure that sweetheart works on IE: (this used to work in previous versions, but we haven't had to support I ...

Using the transform property with the scale function causes elements positioned in the bottom right corner to vanish

Issue specific to Google Chrome and Windows 10 I'm currently working on a flipbook that adjusts content size using transform:scale() based on the user's screen size. There is also a zoom feature that allows users to adjust the scale factor. I ha ...

Adjust the log level on winston in real-time

Is there a way to update the log level dynamically in winston and have it reflect across multiple files? I am facing an issue where changing the logger level in index.js does not affect readfile.js. How can I resolve this? Below is the code snippet: win ...

Create a customized MUI select component with a label, all without the need for assigning an

One issue I am facing is with the Material UI React select component being used multiple times on a page. In the examples, all labeled selects use InputLabel with htmlFor that must match the id of the select. The challenge is that I cannot assign an id t ...

Update my function to be asynchronous by changing async: false to async: true using JQuery and Ajax

I've created a function in a JavaScript class that accesses a PHP file to retrieve information from a database. Although this function works well, I attempted to set the property async: true, and it caused the function to stop working. (I received th ...

Calculate the difference between the current value and the previous value

As I work on developing an app using vue.js, I am currently facing a minor issue. async fetchCovidDataByDay(){ const res = await fetch(`https://api.covid19api.com/live/country/${this.name}/status/confirmed`); const data = await res.json(); this ...

The Microsoft.Azure.WebJobs.Script encountered an issue while attempting to cast an object of type 'System.String' to type 'Microsoft.AspNetCore.Http.HttpRequest' during the return process

I recently encountered an issue with my Azure Function written in JS that is triggered by the Service Bus and generates files to Blob Storage. When attempting to return an HTTP result, I received the following error message: System.Private.CoreLib: Except ...

Struggling to make partial updates to a field within my CRUD update function

Currently, I am working on developing a CRUD application using NodeJS and Express to enhance my backend programming skills. The database being used for this project is MongoDB. This particular project serves as a back office for a shop without any frontend ...

Error message: NodeJS express unknown function or method get()

Currently, I am facing an issue while working with express and Pug (Jade) to render a page as the get() function is returning as undefined along with warnings... I followed these steps: npm install express --save npm install pug --save Here's a sn ...

"What is the best way to transform tab navigation into a dropdown menu with the help

I have a collection of tabs currently on display. I am looking to transform them into a dropdown menu when the screen size changes, making them more responsive. Each set of tabs corresponds to different content. Despite trying various solutions found on s ...

Stop Stripe checkout if all other fields are left empty

I am working on a simple "booking" function using stripe and I encountered this issue. Below is my form code: <form id="formid" action="/checkout" method="POST"> <input type="text" name="kurtuma" id="zaza"> <script src="//check ...

The data provided was deemed incorrect. Modifying the function to include file uploads in Laravel 8 and Vue 2

I've been attempting to create an update function that includes file upload capability. Here is what I have experimented with so far: <b-form @submit.prevent="update" enctype="multipart/form-data"> . . . . <b-form-f ...

Tips for utilizing multiple components in Angular 2

I am a beginner in angular2 and I am attempting to utilize two components on a single page, but I keep encountering a 404 error. Here are my two .ts files: app.ts import {Component, View, bootstrap} from 'angular2/angular2'; import {events} f ...

Encountering the error message 'XMLHttpRequest is not defined' while incorporating getServerSideProps() in NextJS

I'm currently exploring NextJS with SSR and encountering an error when trying to fetch data from a Spotify playlist using the spotify-web-api-js library. This issue only occurs when executing on the server side: error - ReferenceError: XMLHttpRequest ...

Check and validate the adjacent field whenever a change is detected in this field in Angular

Currently, I have a select menu with options and a text field that accepts numerical input. The text field needs to adhere to specific ranges based on the selection from the select menu, which is managed through custom validation. My dilemma lies in trigge ...

How can I designate the file name when using Ajax to export in Excel formatting?

Can you help me with the code to set a specific filename for downloading an Excel file? if(comp_id != "Select Company") { $.ajax({ url: 'includes/export.php', data: { action: 'compreport', 'comp':comp_i ...