user819774
user819774

Reputation: 1514

How to get the index of the checkbox list

I need to loop through the checkbox list. I searched the web and found some code. However I still have a problem - the alert only shows the first time and the index is 0. I referenced this question.

<tr>
  <td>Language:</td>
  <td>
    <asp:checkboxlist runat="server" ID="chk" cssClass="chkClass"></asp:checkboxlist>
    <asp:HiddenField ID="hd" runat="server" />
  </td>
</tr>    
function setcheckbox() {
  $('.chkClass').each(function (i, obj) {
    alert(i);
    if (i == 2) {
      this.prop('checked', true);
    }
  });
}

Upvotes: 0

Views: 157

Answers (1)

Tyler Roper
Tyler Roper

Reputation: 21672

<asp:CheckBoxList cssClass="myClass"> renders as <ul class="myClass">. Therefore, you're not looping through the items, you're looping through the (single) <ul>.

Try adding input[type=checkbox] to your selector, specifying that you're looking for the checkboxes within the <ul>.

function setcheckbox() {
  $('.chkClass input[type=checkbox]').each(function (i, obj) {
    alert(i);
    if (i == 2) {
      this.prop('checked', true);
    }
  });
}

Upvotes: 2

Related Questions