Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get table column index using jQuery?

I have adequate knowledge about jQuery and its usage but today i got into a trouble of getting the column index of matching label inside th element of table using jQuery. I want to get the index of th element having label text as Mobile. The index should be 2 in this case. I am getting the actual index but this is not the correct way of doing it. So i want to know why jQuery is not giving me the right index using index() method.

I have also written the JS Fiddler for this.

jQuery

var elem = $('#tbl th');
var rIndex;
alert('Length : ' + elem.length);
var index = elem.filter(
    function(index){
        var labelText = $(this).find('label').text();        
        //alert(index + ' - ' + labelText);
        var result = labelText == 'Mobile';
        if (result)
            rIndex = index;
        return result;
    }).index();
alert("jQuery Index : " + index);
alert("Actual Index : " + rIndex);

HTML

<table id="tbl">
    <tr>
        <td></td>
        <th><label>Application No.</label></th>
        <td></td>
        <th><label>Name</label></th>
        <td></td>
        <th><label>Mobile</label></th>
        <td></td>
        <th><label>Gender</label></th>
    </tr>
</table>
like image 499
Furqan Safdar Avatar asked May 16 '13 07:05

Furqan Safdar


People also ask

How to get index element in jQuery?

jQuery Misc index() Method The index() method returns the index position of specified elements relative to other specified elements. The elements can be specified by jQuery selectors, or a DOM element. Note: If the element is not found, index() will return -1.


2 Answers

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.

This will give you real index DEMO

elem.each(function(){
    if( $(this).find('label').text()=='Mobile') {
        alert(elem.index(this));
    }
});
like image 175
rahul maindargi Avatar answered Sep 29 '22 11:09

rahul maindargi


You can use rowIndex for row index and event object to get the cellIndex.

this.rowIndex //for row index
e.toElement.cellIndex //for column index

Fiddle below

Fiddle Link

like image 41
Manoj Mohandas Avatar answered Sep 29 '22 12:09

Manoj Mohandas