Search This Blog

Friday, April 4, 2014

Reading ASP.NET Checkboxlist selected text using Jquery

Reading Checkbox list selected items using jquery

*I have posted the same on StackOverflow.

I solved the problem in the following way. My ASP.NET code for the checkboxlist is as below
    <asp:CheckBoxList ID="chkHourly" runat="server" RepeatLayout="Table" 
    RepeatColumns="4"   RepeatDirection="Horizontal">
     <asp:ListItem Value="0">00:00 AM</asp:ListItem>
     <asp:ListItem Value="1">01:00 AM</asp:ListItem>
     <asp:ListItem Value="2">02:00 AM</asp:ListItem>

The generated HTML will look like this below

    <table id="ctl00_chkHourly" border="0">
      <INPUT id=ctl00_chkHourly_0 name=ctl00$chkHourly$0 value="" CHECKED type=checkbox>      
      <LABEL for=ctl00_chkHourly_0>00:00 AM</LABEL></TD>
      <INPUT id=ctl00_chkHourly_1 name=ctl00$chkHourly$1 value="" type=checkbox>
      <LABEL for=ctl00_chkHourly_1>01:00 AM</LABEL></TD>
      <INPUT id=ctl00_chkHourly_2 name=ctl00$chkHourly$2 value="" type=checkbox>
      <LABEL for=ctl00_chkHourly_2>02:00 AM</LABEL>

Please notice that there is a label created besides each input in the table, and when a checkbox is checked, the input's value will be 'on' and what you see as an option is the label's text, in my case I needed the text, but to get the value also in a round about away, I would read the name of the individual input fields that are checked. Please see the code below that I have written to read the text selected and also the name of the input selected so that I can strip it and read the value if needed.

    var postData = new Array();
    $("[id*=chkHourly] input[type=checkbox]:checked").each(function () {
     if (postData.length > 0) {
      alert("Selected Text(s): " + postData);
     else {
      alert("No item has been selected.");