1

I have the following function:

function LoadColWidth(thewidtharray) {

    for (i = 0; i < thewidtharray.length; i++) 
    {
        $('#MyGrid .tr:first').eq(i).width(thewidtharray[i]);
    }
};

var NarrowWidth = new Array(70, 72, 97, 72, 97, 72, 96, 76, 76, 76, 76, 75);

I'm calling LoadColWidth with different arrays as the parameter and the goal is to resize the width of columns. I'm struggling with the jquery call: it's supposed to loop through each columns by index but it's not working. Any suggestions?

Thanks.

1 Answer 1

1

Select the <td> elements in the first row, and iterate over them using the each()(docs) method.

Inside the .each(), use the index parameter it provides to select from your Array of widths.

 // Use the "index" parameter--------------v
$('#MyGrid tr:first > td').each(function( i ) {
    $(this).width( thewidtharray[i] );
});

Or here's an alternative if you're using jQuery 1.4.1 or later:

 // Use the "index" parameter---------------v
$('#MyGrid tr:first > td').width(function( i ) {
    return thewidtharray[i];
});
Sign up to request clarification or add additional context in comments.

6 Comments

This works. However, I'm actually looking to loop only through the columns of a certain class and I haven't been able to make the code look to see if the column is of the class .MyClass. Working on it but kinda stuck...
@frenchie: I just noticed that your code has a misplaced . before tr:first, which I ended up copying. Fixed. If you're only targeting td elements with a certain class, you'd do $('#MyGrid .tr:first > td.myClass'). I may be able to give a better answer if you provide a sample of your table in your question.
So, should I remove the dot or keep it? The table is a gridview; some columns are of class MyClass and some are not.
@frenchie: I made the same copy/paste error in my comment, but fixed it in my answer. You're selecting a <tr> element, so you do not want the . before tr. $('#MyGrid tr:first > td.myClass')
...or use th if that's what you have in the first row $('#MyGrid tr:first > th.myClass')
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.