Home > database >  How to add a table header to this div-table within a script?
How to add a table header to this div-table within a script?

Time:01-21

I got this div-table populated dynamically, but I can't find a way to add a header to it, given the way this is being built.

HTML piece:

<div  id="sidebar-record-block"></div>

This is the script populating the table dynamically:

function showRecord(record) {
    if (record.length) {
      for (var i = 0; i < record.length; i  ) {
        // build field name on the fly, formatted field-1234
        var str = ''   i;
        var fieldId = 'field-'   ('0000'   str).substring(str.length)

        // If this field # doesn't already exist on the page, create it
        if (!$('#' fieldId).length) {
          var newField = $($.parseHTML('<div id="' fieldId '"></div>'));
          $('#sidebar-record-block').append(newField);
        }

        // Replace content of the field div with new record
        $('#' fieldId).replaceWith('<div id="' fieldId '" ></div>');
        $('#' fieldId).append('<input id=checkBox type="checkbox"</input>')
                      .append($('<div >'   record[i].heading   '</div>'))
                      .append('<div >'   record[i].cellval   '</div>')             
      }  
    }

Here's how css is:

.div-table {
    display: table;
    width: auto;
    border-spacing: 3px;
  }

  .div-table-row {
    display: table-row;
    width: auto;
    clear: both; 
 }

  .div-table-td,
  .div-table-th {
    display: table-cell;
    width: 190px;
    background-color: rgb(245, 241, 239);
  }

Here's the expected result: enter image description here Appreciate your help!

CodePudding user response:

Actually you have almost anything you need yet. The trick is just adding the headings for your rows as a different styled row element to your custom table.

For example:

.div-table {
    display: table;
    width: auto;
    border-spacing: 3px;
  }

  .div-table-row {
    display: table-row;
    width: auto;
    clear: both; 
 }

  .div-table-td,
  .div-table-th {
    display: table-cell;
    width: 190px;
    background-color: rgb(245, 241, 239);
  }
  
  .div-table-header {
    display: table-cell;
    width: 190px;
    text-align: center;
  }
<div  id="sidebar-record-block">
  <div >
    <div>Sel</div>
    <div >Color</div>
    <div >Hex</div>
  </div>
  <div >
    <input type="checkbox">
    <div >amarelo suave</div>
    <div >EEEA97</div>
  </div>
  <div >
    <input type="checkbox">
    <div >verde</div>
    <div >00FF00</div>
  </div>
</div>

Creating this dynamically at runtime isn't much different from the code you already have.

Just add the following at the beginning of your for-loop:

if(i==0) {
   $('#sidebar-record-block').append($($.parseHTML('<div ><div>Sel</div><div >Color</div><div >Hex</div></div>')));
      }
  •  Tags:  
  • Related