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>
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.
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));
}
});
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With