I have a table with different values. First column contains labels. I need to get the width of the widest label. I assume I need some sort of a loop, but then what?
var w = 0;
$("#myTable tr td:first").each(function(){
if($(this).width() > w){
w = $(this).width();
}
});
var widestTdLabel=0;
$('#myTable td').each(function(index) {
if($(this).find('label').width()>widestTdLabel)
widestTdLabel=$(this).find('label').width();
});
alert(' width of the widest label is:'+widestTdLabel);
Try this:
var widest;
var widestWidth = 0;
$("#myTable td").each(function(t) {
if($(this).width() > widestWidth){
widest = $(this);
widestWidth = $(this).width();
}
});
//Now widest points to the widest element
Note I tracked the actual width separately from the widest element. An alternate solution without this method would be to initialize widest to a dummy element with width = 0 and just compare $(this).width() with widest.width()
EDIT: Or, alternately, now that I realize you wanted only the width and not the actual element, you could use this version:
var widestWidth = 0;
$("#myTable td").each(function(t) {
widestWidth = Math.max(widestWidth, $(this).width());
});
I assume that you have one <label>
element inside all <td>
elements in the first column (since it makes no sense to compare the widths of the <td>
elements themselves — within the same column they are equally wide (not considering colspan != 1
)):
var widestLabel = 0;
$("#myTable td:nth-child(1) label").each(function() {
widestLabel = Math.max(widestLabel, $(this).width());
});
This should work - it will go through each of the tds (in myTable) and find the widest:
var widest = 0;
$("#myTable tr td:first").each(function()
{
widest = ($(this).width() > widest) : $(this).width() : widest;
});
alternatively:
var widest = 0;
$("#myTable tr td:first").each(function()
{
if($(this).width() > widest){
widest = $(this).width()
}
});