count selected gridview rows in javascript

Count Selected Gridview Rows in Javascript

Have you ever encountered a situation where you need to count the number of selected rows in a gridview using Javascript? If yes, then you are in the right place. In this post, I will share with you how to count selected gridview rows in Javascript.

Method 1: Using a Loop

The first method to count selected gridview rows in Javascript is to loop through all the rows and check if they are selected or not. Here is the code:


var gridview = document.getElementById("myGridview");
var count = 0;

for (var i = 0; i < gridview.rows.length; i++) {
    if (gridview.rows[i].cells[0].getElementsByTagName("input")[0].checked) {
        count++;
    }
}

console.log("Number of selected rows: " + count);
  • var gridview = document.getElementById("myGridview");: Gets the gridview element by its ID.
  • var count = 0;: Initializes a variable to store the count of selected rows.
  • for (var i = 0; i < gridview.rows.length; i++) { ... }: Loops through all the rows of the gridview.
  • if (gridview.rows[i].cells[0].getElementsByTagName("input")[0].checked) { ... }: Checks if the checkbox of the current row is checked or not.
  • count++;: Increments the count if the checkbox is checked.
  • console.log("Number of selected rows: " + count);: Outputs the count of selected rows to the console.

Method 2: Using jQuery

If you are using jQuery in your project, then you can use the following code to count selected gridview rows:


var count = $("#myGridview input[type='checkbox']:checked").length;

console.log("Number of selected rows: " + count);
  • $("#myGridview input[type='checkbox']:checked"): Gets all the checked checkboxes inside the gridview using the jQuery selector.
  • .length: Gets the number of selected checkboxes.
  • console.log("Number of selected rows: " + count);: Outputs the count of selected rows to the console.

These are the two methods to count selected gridview rows in Javascript. You can choose any method that suits your project requirements. I hope this post was helpful to you. If you have any questions or suggestions, feel free to leave a comment below.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe