Niranjan Godbole
Niranjan Godbole

Reputation: 2175

how to loop through gridview using jquery and check if any checkbox is checked

I am developing jquery based application. I have one asp.net gridview with checkboxes in every row. I want to check if any of the checkboxes checked or not. I am looping through gridview rows and checking any checkbox is checked or not as below.

var ResultArrayFirst = [];
        $('#<%= gdvRegretletter.ClientID %> input[type="hidden"]').each(function () {
            if ($(this).closest('tr').find('input[type="checkbox"]').prop('checked', true))
            {
                ResultArrayFirst.push($(this).val());
            }

        });
        alert(ResultArrayFirst);

My above code does not works. As soon as above code is executed, all checkboxes will check. I am not sure what i Am missing here. Any help would be appreciated. Thank you.

Upvotes: 1

Views: 2680

Answers (3)

Curiousdev
Curiousdev

Reputation: 5788

Just give a class to checkbox as example chk and than use .map() instead of each loop it will get items in an array please find below single line of code to achieve

var selected =  $(".chk:checked").map(function(i,el){return el.value;}).get();

As well as if you wants to just check if any check boxes is checked or not you can do as below it will return a bool value

$(".chk").is(":checked")

Upvotes: 1

Hemal
Hemal

Reputation: 3760

You can use :checked selector of jquery

 $('#<%= gdvRegretletter.ClientID %> input[type="hidden"]').each(function () {
     if ($(this).closest('tr').find('input[type="checkbox"]').is(":checked"))
     {
         ResultArrayFirst.push($(this).val());
     }

  });

Upvotes: 2

kapantzak
kapantzak

Reputation: 11750

To check if a checkbox is checked, use this:

if (checkbox.is(':checked')) {
   // Do your stuff
}

So, change your code like this:

if ($(this).closest('tr').find('input[type="checkbox"]').is(':checked'))
{
   ResultArrayFirst.push($(this).val());
}

Upvotes: 3

Related Questions