Question

I have two HTML buttons, one named 3days and other named week. Based on the click of any of these buttons I need to create a dynamic table with Fixed Headers but dynamic column. For example, suppose I clicked on 3days button,then the resultant table should be with 2 fixed headers and 3 dynamic column with 1,2,3 as name of the column. LIkewise if clicked on week button then HTML table should be with 2 fixed headers and 7 columns with column name as 1,2,3,4,5,6.

I have a HTML table but how to create it dynamically using ajax and jQuery? I am not getting that.

HTML table..

 <div id="table">
    <table style="height:500px">
    <thead>
    <tr>
        <th>Column 2</th>
        <th>Column 3</th>
   </tr>
 </thead>
 <tbody>
    <tr><td>Cell 1</td><td>Cell 2</td><td>Cell 3</td><td>Cell 4</td>
 </tbody>
 </table>
 </div>

Please help me to resolve this..

Was it helpful?

Solution

You want something like this:

HTML

<div id="table">
    <table>
        <thead>
            <tr>
                <th>Column A</th>
                <th id="flex-header">Column B</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td></td>
                <td></td>
            </tr>
        </tbody>
    </table>
</div>
<button value="3">3</button>
<button value="7">7</button>

JS

$(function () {
    $("button").click(function (e) {
        var cols = $(this).val();

        // You'll want to do something here to get the column data
        var data = $("<tr></tr>").append($("<td>Col 0</td>"));
        for (i = 0; i < cols; i++) {
            data.append($("<td>Col " + (i + 1) + "</td>"));
        }
        $("#flex-header").prop("colspan", cols);
        $("#table table tbody").html("").append(data);
    });
});

jsfiddle

This will allow you to change around the number of columns easily. Of course, there are other ways to do it (like the other answer with toggling tbody elements) but this should give you a little flexibility with the column counts.

EDIT
Here is an updated jsfiddle with the table toggle behavior.

OTHER TIPS

Updated Code:

   $("table").hide();
$("#3").click(function(){
    $("table").show();
    $("th:gt(2)").hide();  
    $("td:gt(2)").hide();  
});

$("#7").click(function(){
     $("table").show();
    $("th:lt(7)").show();  
    $("td:lt(7)").show();  
});

Demo: http://jsfiddle.net/hsakapandit/3kUjR/2/

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