Question

I have one table which display data as from Dynamic Content, I want to make table width 100% when there is 6 cols. and table width auto if less the 5 cols.

I tried with CSS but, when there is only two cols, it expand two cols to full width while have table 100% width and looks awkward.

Is there any Javascript, jQuery script available to get this result?

Was it helpful?

Solution

Using jQuery and ensuring you choose the first row in the table body in case the thead has a different layout.

function setTableWidth(tableId) {

    var $tbl = $('#'+tableId);
    var newWidth = $tbl.find('tbody>tr:eq(0)>td').length > 5 ? '100%' : 'auto';
    $tbl.width(newWidth)

 }

OTHER TIPS

Depending on how you're loading the dynamic content, there might be an easier way, but this function should do what you need:

function setTableWidth(tableId) {
    myTable = document.getElementById('tableId');
    if (myTable.getElementsByTagName('tr')[0].getElementsByTagName('td').length > 5)
        myTable.style.width = '100%';
    else
        myTable.style.width = 'auto';
 }

Note though, that it won't work if any of the cells in the first row have a colspan. It's simply counting the number of columns in the first row and setting the width based on that.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top