John Smith
John Smith

Reputation: 6259

Create rowspans with jquery

I append the data from a json-object to a table:

var array1 = $.map(data, function (field, i) 
{
    return '<tr><td>' + field.date + '</td><td>' + field.art + '</td><td class="san' + field.art +'">' + field.text + '</td></tr>';
});

$('#TableBody').append(array1.join(''));

enter image description here

Actually this works pretty good and i get a output like this:

<tbody id="TableBody">
<tr><td>18.02.2014</td><td>D</td><td class="sanD">Was soll ich sagen</td></tr>
<tr><td>18.02.2014</td><td>DD</td><td class="sanDD">hallo</td></tr>
<tr><td>17.02.2014</td><td>R</td><td class="sanR">Erster Versuch</td></tr>
</tbody>

But i would like to have such an output: Means that same field.date have only one row:

<tbody id="TableBody">
<tr><td rowspan="2">18.02.2014</td><td>D</td><td class="sanD">Was soll ich sagen</td></tr>
<tr><td>DD</td><td class="sanDD">hallo</td></tr>
<tr><td>17.02.2014</td><td>R</td><td class="sanR">Erster Versuch</td></tr>
</tbody>

How can i achieve this? Thanks

Fiddle: http://jsfiddle.net/V2mmw/2/

Upvotes: 2

Views: 56

Answers (2)

Alessandro Gomes
Alessandro Gomes

Reputation: 521

I think that you need something like this, but i used $.each function:

var html = "";
var arr = new Array();

$.each(data, function (i, field) {    

    var rowspanTest = $.grep(data, function (elem) {
        return elem.date === field.date;
    }).length;    

    if(jQuery.inArray( field.date, arr ) == -1){    
        html += '<tr><td rowspan=' + rowspanTest + '>' + field.date + '</td><td>' + field.art + '</td><td class="san' + field.art +'">' + field.text + '</td></tr>';
        arr.push(field.date);
    }else{
        html += '<tr><td>' + field.art + '</td><td class="san' + field.art +'">' + field.text + '</td></tr>';        
    }
});

$('#TableBody').append(html);

Demo JSFiddle

Upvotes: 3

zord
zord

Reputation: 4783

Here is a function that does what you want:

function mergeSameDates() {
    var $firstItem, 
        sameCount = 0;
    $("#TableBody tr td:nth-child(1)").each(function (index, item) {
        var $item = $(item);
        if ($firstItem === undefined || $item.text() !== $firstItem.text()) {
            $firstItem = $item;
            sameCount = 1;
        } else {
            sameCount += 1;
            $firstItem.attr("rowspan", sameCount);
            $item.remove();
        }
    });
}

Here is an updated demo fiddle.

Upvotes: 3

Related Questions