0

I am creating a table using Javascript that will input the cell values dynamically and also the cell widths are computed using a complex formula, finally in terms of percentage. Now I am unable to set cell widths in Javascript according to the widths I have obtained from calculation. In a broader sense, each row may have columns of different widths and of course number of columns in each row will also differ. How to crack this logic?

It may look like this ...

1
  • It is not possible to be achieved using cell width. It is only achieved by colspan. Commented Nov 23, 2013 at 8:06

2 Answers 2

1

You could use one table element for each row and set the td width css property using javascript based on the results of your computations:

<table id="row1">
    <tr>
        <td>a</td>
        <td>b</td>
    </tr>
</table>
<table id="row2">
    <tr>
        <td>c</td>
        <td>d</td>
    </tr>
</table>

And javascript:

var cells = document.getElementsByTagName('td');
var calculatedWidths = [25, 100, 100, 25];

for(var i = 0; i < cells.length; i++){
    cells[i].style.width = calculatedWidths[i] + "px";    
}

See this jsFiddle.

Sign up to request clarification or add additional context in comments.

3 Comments

what is the difference between px and percent coz ultimately alignment will happen only if 100% filling happens
one more point to added here is that, you have mentioned widths of td for only one row but successive rows will have td widhths different to this...
A px is a unit of measurement. Percent is based on the width of its parent element. And I don't understand your second comment. You can set the td width for any cell using this method.
0

var tds = document.getElementsByTagName('td');

for (var i = 0; i < tds.length; i++) tds[i].style.width = '2px';

1 Comment

This doesn't allow for variable width cells (<td>'s) in the same column.

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.