javascript - Find table row index that contains text JQuery -


i trying find table row index link on table. code trying, returning value 3. have 2 many rows on page. code -

table (example) -

<table>   <tbody>    <tr>     <td>      <div>        <a herf="my link here" onclick="findindex(rank1)">rank1</a>      </div>     </td>    </tr>   </tbody> </table> 

jquery -

function findindex(rname) {     var val = $('table tbody tr td div a:contains(' + rname + ')').index();     alert(val); }); 

please me how find table row index value.

thanks

when call index() on selector, you're in fact getting index of a element. text selector working fine, after finding element mached text, need find it's tr , it's index:

$('table tbody tr td div a:contains("' + rname + '")').closest("tr").index(); 

demo

also, have syntax errors:

onclick="findindex(rank1)"  

should be:

onclick="findindex('rank1')"  

or better:

onclick="findindex(this)"  

and function:

function findindex(element) {     var val = $('table tbody tr td div a:contains("' + element.innertext + '")').closest("tr").index();     alert(element.innertext + "=" + val); }; 

demo

note have added quotes css selector:

'table tbody tr td div a:contains("' + element.innertext + '")'                                   ^                    ^ , 

to produce result 'table tbody tr td div a:contains("rank1")'


now, best thing can jquery:

remove onclick event attribute anchor elements , add class:

<a herf="my link here" class="rank-anchor">rank1</a> 

then bind event on document load table:

$("table").on("click", "a.rank-anchor", function() {     var index = $(this).closest("tr").index();     alert(index); }); 

in event function, can see don't need full selector a element, have element, can use this find tr. in case don't need find element it's content well, event being called fron already.

demo


Comments

Popular posts from this blog

magento2 - Magento 2 admin grid add filter to collection -

Android volley - avoid multiple requests of the same kind to the server? -

Combining PHP Registration and Login into one class with multiple functions in one PHP file -