Vladi
Vladi

Reputation: 1990

get a list of Gridview checked items

I have a dynamic GridView of students that number of rows it depends on database information

example of my page/table

I want that after I press the button i will get a list of ONLY checked PersonID in array/list.
I don't know how to write this JavaScript/jQuery function.

CheckBox:

<asp:CheckBox CssClass="chk" ID="Checkbox" runat="server" Text='<%# Bind("PersonID") %>'></asp:CheckBox>

Button:

<asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="myClosure1()" />

JavaScript:

<script type="text/javascript">

function myClosure1() {
    $('.chk').each(function () {
        var chkbox = $(this).children('input').get(0);
        if (chkbox.checked) {

        }
    });
}

</script>

I'm not sure it even gets inside the $('.chk').each

Edit example to the picture I upload it will publish numbers 1,2,4 beacuse i check them

Upvotes: 0

Views: 944

Answers (2)

Win
Win

Reputation: 62260

For that case, I'll add another hidden filed control. Then the rendered output will be like this -

<span class="chk">
   <input id="GridView1_Checkbox_0" type="checkbox" name="GridView1$ctl02$Checkbox">
      <label for="GridView1_Checkbox_0">1</label>
</span>
<input type="hidden" name="GridView1$ctl02$HiddenField1" 
      id="GridView1_HiddenField1_0" value="1">

ASP.NET Checkbox control is rendered inside span tag, so you will need to access them as .chk input in jQuery.

<button type="button" id="btnAll">Select All</button>
<asp:GridView ID="GridView1"
    AutoGenerateColumns="False"
    runat="server" DataKeyNames="PersonID">
    <Columns>
        <asp:BoundField DataField="PersonID" HeaderText="PersonID" />
        <asp:TemplateField>
            <ItemTemplate>
                <asp:CheckBox CssClass="chk" ID="Checkbox"
                    runat="server" Text='<%# Bind("PersonID") %>'></asp:CheckBox>
                <asp:HiddenField runat="server" ID="HiddenField1"
                    Value='<%# Bind("PersonID") %>' />
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>
<div id="result"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript">
    var personIDs;
    $("#btnAll").click(function () {
        personIDs = []; // Clear data
        $(".chk input:checked").each(function () {
            // 'this' is a checkbox, so we need to go up to parent span tag.
            personIDs.push($(this).parent().next('input[type=hidden]').val());
        });
        $("#result").text(personIDs);
    });
</script>

Upvotes: 1

JFT
JFT

Reputation: 101

// Each row of the table
$("#table tr").each(function(){ 
        // get checkbox id and look for CheckStatus.
});

Upvotes: 0

Related Questions