简体   繁体   中英

Dynamically Adding A Row To Bottom of Table

Using JavaScript, within the context of an AngularJS application, I am trying to add a row at the end of a table that displays the sum total of a particular column.

In the following code:

  var table = document.querySelector('.table');
  var row = table.insertRow(0);
  var cell1 = row.insertCell(0);
  var cellData = document.createTextNode('Total ' + '$' + this.totals);
  cell1.appendChild(cellData);
  row.appendChild(cell1);

Using insertRow(-1) isn't working. The only way I am able to see my row is if I pass in zero as the first parameter. As in insertRow(0), but the row is inserted as a row in the table header.

Here's my full code:

import { digest, showLoader } from 'act/services/events';
import 'act/components';
import Searcher from 'act/services/lists/searcher';
import * as moment from 'moment';
import * as api from '../services/totals';
import {header, dev} from 'act/services/logger';
import {goToError} from 'act/services/controller-helpers';
import '../components/store-total';
const defaultStartDate = moment().startOf('day');

export default class StoreTotalsController {
  constructor() {
    this.attendantNames = [];
    this.stores = [];
    this.emptyResult = true;
    this.totals = 0;
  }

  getAttendants() {
    showLoader('Searching');
    const baseUrl = '/src/areas/store-totals/services/tender-total-data.json';
    const getStores = new Request(baseUrl, {
      method: 'GET'
      });
    fetch(getStores).then(function(response){
      return response.json();
    }).then(resp => {
    if (!(resp[0] && resp[0].error)) {
      this.attendantNames = resp.stores[0].attendants;
      this.attendantNames.forEach(a=>{
        this.totals += a.total;
        console.log(this.totals);
      })

      var table = document.querySelector('.table');
      var row = table.insertRow(0);
      var cell1 = row.insertCell(0);
      var cellData = document.createTextNode('Total ' + '$' + this.totals);
      cell1.appendChild(cellData);
      row.appendChild(cell1);

      this.emptyResult = false;
      this.errorMessage = null;

    } else {
      this.errorMessage = resp[0].error.name;
    }
    digest();
    showLoader(false);
    });
  }

  searchIfReady() {
    if (this.search && this.date && this.date.isValid()) {
      this.getSearch();
    }
  }

  updateDate(date) {
    this.date = moment(date).startOf('day');
    this.searchIfReady();
  }
}
StoreTotalsController.$inject = ['$stateParams'];

A few ways to go about this, bind to a newly updated array with an ngFor, and so on. Templates, binding, all sorts of new and fancy ways. Ultimately the advice would probably be, "don't use a table".

But if you must use a table, and all you really want to do is append another HTML row, this old trick works (though it may get the Angular chorus howling). Be aware you're manipulating innerHTML. You could also update this using document fragments to make it a bit more OOP-ish.

Why tbody? Select the table with querySelector and console.log it. You'll see the rows are wrapped in a tbody.

This is the ultra naive version. Works though. Back in the AngularJS days sometimes this sort of thing just got you home on time.

<html>
<head>
<body>
    <table>
    <tr>
    <td>Row 1</td>
    </tr>
    </table>

    <button onclick="addRow ()">Click Me</button>

    <script>
        function addRow ( ) {
        const tbody = document.querySelector ( 'tbody' );
        let inner = tbody.innerHTML;
        inner += '<tr><td>Row 2 (compute value as necessary)</td></tr>';
        tbody.innerHTML = inner;
    }
    </script>
</body>
</html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM