Wasim Shaikh Wasim Shaikh - 1 month ago 7
jQuery Question

Dynamic width of Table as per column

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?

Answer

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)

 }
Comments