Search code examples
jquerycheckboxlist

how to get the selected index of check box from checkboxlist control using jquery?


Greetings, how to get the selectedindex of check box from checkboxlist control using jquery?

Update:

This code is giving me selected index equal 0 please advive

<asp:CheckBoxList ID="chkListGroups" runat="server" 
                    style="position:absolute; top: 1115px; left: 745px; bottom: 371px;" 
                    DataSourceID="SqlDSGroups" DataValueField="Groups" 
                    onclick="test()">
                </asp:CheckBoxList>


....................
java script function
.....................
  function test(){
  $('#<%=chkListGroups.ClientID %>').click(function() {
                var selectedIndex = $('#<%=chkListGroups.ClientID %>').index($(this));


                alert(selectedIndex);


            });
        }

Solution

  • Use a selector for the collection, then use index with the element that you are interested in, here the one that is checked.

    var checkboxes = $('input:checkbox');
    var selectedIndex = checkboxes.index(checkboxes.find(':checked'));
    

    To get the index of a clicked checkbox use:

    $('input:checkbox').click( function() {
        var selectedIndex = $('input:checkbox').index( $(this) );
        ... now do something with it...
    });
    

    EDIT: Based on your code sample:

    var checkboxes = $('#<%=chkListGroups.ClientID %>').find('input:checkbox');
    checkboxes.click(function() { 
        var selectedIndex = checkboxes.index($(this)); 
        alert(selectedIndex); 
    
    });