1. Who are you?

Get jquery index of td element

I have a 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 a specific td that has its own checkbox. For example, there should be 1. But I get 0 every time, which seems to be the index of the row. Here is the jquery code I 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 to get the index of a particular td? Thanks

+6
source share
2 answers

You can do it with

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

You just need to go from the checkbox to <td> , at which point a direct .index call 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 jQuery relative to its sibling elements.

Look at the action .

Since you are doing this inside a loop, it would be more appropriate

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

Change the line as follows:

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

This will give you the td index, which is the parent of the input you selected in the jquery selector.

+2
source

Source: https://habr.com/ru/post/915880/


All Articles