Reputation: 2674
I'm trying to build a table when users can merge rows and columns. I've got the code for columns working OK, and rows are almost there too - however, when I alter a rowspan from 3 down to 2, I get an extra column added.
You can see what I mean in this fiddle.
And here's my code:
function growRow(td, span, cell_content) {
var cell_content = (typeof cell_content === 'undefined') ? '<td></td>' : cell_content
var row = td.closest("tr")
var index = td.index()
var old_span = (typeof td.attr('rowspan') === 'undefined') ? 1 : Number(td.attr('rowspan'))
var table = row.parents('table')
var content
td.attr('rowspan', span)
if (span > old_span) {
// If we want to merge cells, this is easy
var selector = "tr:lt(" + (span - 1) + ")"
row.nextAll(selector).each(function () {
// Grab the content from each cell
content = $("td:eq(" + index + ")", $(this)).html()
$("td:eq(" + index + ")", $(this)).remove()
})
// Get the next cell down
row = $('tr:eq('+ span +')')
// Append the content to make it look as though the cells are 'moving down'
row.find('td:eq('+ index +')').html(content)
} else {
// This is where I'm having problems
// Get the number of cells we need to put back
count = old_span - span
// Work through the rows
for (var i=0; i < count ; i++) {
// Get the row at the right index
r = $(row.nextAll()[i])
if (index == 0) {
// If we're at the beginning of a row, we need to prepend
r.prepend(cell_content)
} else {
// Otherwise use nth-child to append in the right place
r.find('td:nth-child(' + index + ')').after(cell_content)
}
}
}
return td
}
Any help would be hugely appreciated, as I've been on this for DAYS now!
Upvotes: 0
Views: 1594