Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get the jquery index of "td" element

Tags:

jquery

I have markup

 <table>
    <tr id="1">
        <td colspan="4">
            <p class="que">
                1. Who are you?</p>
        </td>
    </tr>
    <tr class="ans">
        <td>
            <input type="checkbox" />Student
        </td>
        <td>
            <input type="checkbox" checked="true" />Developer
        </td>
        <td>
            <input type="checkbox" />Other
        </td>
        <td>
            <input type="text" />
        </td>
    </tr>

</table>​​​

Here I want to get the index of the particular td which has its checkbox checked. For example here it should be 1. But I m getting 0 eachtime which seems like the index of the row. Here is the jquery code I have used.

   var answers = $('table tr.ans');
 $.each(answers, function () {
  var answer = $(this).find("input[type='checkbox']:checked").index(); 
    alert(answer);                   
  });​

and here is the fiddle How do I get the index of the particular td? Thanks

like image 266
Paras Avatar asked May 16 '12 07:05

Paras


People also ask

How to get td index using jQuery?

jQuery: code to get TD text value on button click. text() method we get the TD value (table cell value). So our code to get table td text value looks like as written below. $(document). ready(function(){ // code to read selected table row cell data (values).


2 Answers

You can do it with

$("table tr.ans input[type='checkbox']:checked").parent().index();

You simply need to navigate from the checkbox back up to the <td>, at which point stright calling .index does the trick:

If no argument is passed to the .index() method, the return value is an integer indicating the position of the first element within the jQuery object relative to its sibling elements.

See it in action.

Since you are doing this inside a loop, a more proper fit would be

var answer = $(this).find("input[type='checkbox']:checked").parent().index();
like image 135
Jon Avatar answered Oct 02 '22 19:10

Jon


Change the line to this:

var answer = $(this).find("input[type='checkbox']:checked").parent().index(); 

This will give you the index of the td that is the parent of the input you have selected in your jquery selector.

like image 41
Øyvind Bråthen Avatar answered Oct 02 '22 19:10

Øyvind Bråthen