Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

how to make colspan of table footer flexible with javascript/jQuery

$(document).ready(function() {
  const header = ["Info", "Info", "Info", "Info", "Sum1", "Sum2", "Info", "Sum3", "Info", "Info", "Sum4"];
  const needles = ["Sum1", "Sum2", "Sum3", "Sum4"];

  const spans = []; // new array
  let cursor = 0; // cursor
  spans[cursor] = {
    text: '',
    colspan: 0
  };

  for (let i = 0; i < header.length; i++) {
    if (!needles.includes(header[i])) { // if not included, ++colspan
      spans[cursor].colspan++;
    } else {
      if (i !== 0) cursor++; // only needed when we have a needle
                             // in the first header element

      // here I create the new objects
      // with the text Sum1, Sum2, etc
      // and colspan=1
      spans[cursor] = {};
      spans[cursor].text = header[i];
      spans[cursor].colspan = 1;

      if (i === header.length - 1) continue; // if I am at the end 
                                             // of the header array,
                                             // skip the next block


      // if the next element in the header array is not included
      // in needles, I already create a new element with
      // colspan = 0 for the next loop.
      // If the next element is also in needles it's not necessary
      // as it will be catched by else{} block in the next loop
      if (!needles.includes(header[i + 1])) {
        cursor++;
        spans[cursor] = {};
        spans[cursor].text = '';
        spans[cursor].colspan = 0;
      }
    }
  }

  console.log(spans);

  for (const span of spans) {
    $('#testTable tfoot tr').append(`<th colspan="${span.colspan}">${span.text}</th>`);
  }
});
 
PREVIOUS NEXT
Tagged: #colspan #table #footer #flexible
ADD COMMENT
Topic
Name
6+2 =