views:

37

answers:

1

Hi All, How to create below mentioned table structure in jquery/javascript:

  <table>
    <tr>
        <td>
            one
        </td>
        <td>
            two
        </td>
        <td>
            three
        </td>
    </tr>
    <tr>
        <td>
           single
        </td>

    </tr>
      <tr>
        <td>
            one
        </td>
        <td>
            two
        </td>
        <td>
            three
        </td>
    </tr>
     <tr>
        <td>
           single
        </td>

    </tr>
</table>

i.e. alternate row is having 3/ 1 cols.

+1  A: 

This should suffice:

$(document).ready(function(){
    var $myTable = $("<table></table>");
    var $myRow;
    var rowCount = 10; //or whatever you want
    var cellCount = 1;
    var i = 0;
    for (i=0; i<rowCount; i++){
        $myRow = $("<tr></tr>");
        cellCount = (i%2 === 0)? 3 : 1;

        for (var j=0; j<cellCount; j++){
           $myRow.append("<td>a</td>") 
        }

        $myTable.append($myRow);
    }

    $("body").append($myTable); //if you want to add it to your document.
});​

Check out the JSFiddle: http://jsfiddle.net/ZbJ3v/

This, of course doesn't add in your "one" "two", etc (I just have 'a' to denote the structure) but I assumed from your question that you just wanted the structure.

Edit for comment below. The loop block would look something like:

    for (i=0; i<rowCount; i++){
        $myRow = $("<tr></tr>");
        if (i%2 === 0){
           $myRow.append("<td>aa.bb</td>") 
           $myRow.append("<td>aa.cc</td>") 
           $myRow.append("<td>aa.dd</td>") 
        }else{
           $myRow.append("<td>xx</td>") 
        }

        $myTable.append($myRow);
    }

Avaliable on this jsfiddle: http://jsfiddle.net/WPJ5q/

James Wiseman
Thanks, but lets say i have to enter diff data, in that case how to modify the code:lets say in case of 3 <td> it is <td>aa.bb</td><td>aa.cc</td><td>aa.dd</td> and for single <td> it is <td>xx</td>
Wondering
ok, i have modified the code a bit, it worked.Thanks.
Wondering
And a vote up as well?
James Wiseman