.index () inside .each () always returns 0 when the check box is in a table or div

advertisements

Please help me with this issues.

i'm going to get the index number of checked checkbox array which reside in a html table, but each time i alert the each of checkbox's index inside .each() , its will return 0 for each loop.

but this code will work if i remove the table and all its tr and td (leave the two checbox alone)

my jquery code:

function notify() {

               $("input[type = 'checkbox']:checked").each(function(){
               alert($(this).index());  /*always return zero when the check[] inside a table or div */
               });
           }

function main() {

        $("input[type = 'button']").click(notify);
}

$(document).ready(main);

my html code:

 <table>
   <tr><td>
    <input type='checkbox' name='check[]' />
   </td><td>
   <input type='checkbox' name='check[]' />
   </td> </tr>
 </table>
<input type='button' name='button' value='ok'/>

this is the link to my code in jsfiddle


This is probably what you are looking for. SInce you are wrapping your check boxes in td's, why not find the index of td

[Demo]

function notify() {

    $("input[type = 'checkbox']:checked").each(function () {
        alert($(this).parents('td').index());
    });
}