如何使用Jquery / Javascript在动态创建的表中添加id

时间:2018-05-16 09:55:41

标签: javascript jquery html

当用户点击Add Row按钮时,我正在成功创建动态表。

<table id="billTable" style="">
  <tr>
    <th>Sr no</th>
    <th>Product/Service </th>
    <th>HSN / ACS</th>
    <th>UOM</th>
    <th>Qty</th>
    <th>Rate</th>
    <th>Amount</th>
  </tr>
  <tr>
    <td><div id="Psno" >1</td>
    <td><div id="PproductName" contenteditable>Product/Service</td>
    <td><div id="PHSN" contenteditable></td>
    <td><div id="PUOM" contenteditable>BOXES</td>
    <td><div id="PQty" contenteditable>6</td>
    <td><div id="PRate" contenteditable>6.10</td>
    <td><div id="PAmount">--</td>
  </tr>
</table>

<div class="pull-right">
  <label><button type="checkbox" id="AddTable" value=""> Add Row</label>
</div>

<script>
$('#AddTable').click(function() {
  $("#billTable").append("
  <tr>
    <td><div contenteditable></div></td>
    <td><div contenteditable></div></td>
    <td><div contenteditable></div></td>
    <td><div contenteditable></div></td>
    <td><div contenteditable></div></td>
    <td><div contenteditable></div></td>
    <td><div contenteditable></div></td>
  </tr>");
});
</script>

但我很困惑如何在用户点击添加行时添加动态ID。这样我就可以用JSON格式将所有数据发送到服务器。

请告诉我以哪种方式生成ID

2 个答案:

答案 0 :(得分:0)

如果你在谈论只是为每一行生成一个ID?然后,这可以通过使用count变量简单地完成。例如,

HTML

<table id="billTable" style="">
  <tr>
    <th>Row ID</th>
    <th>Sr no</th>
    <th>Product/Service </th>
    <th>HSN / ACS</th>
    <th>UOM</th>
    <th>Qty</th>
    <th>Rate</th>
    <th>Amount</th>
  </tr>
  <tr>
    <td><div id="RowId_0">0</div></td>
    <td><div id="Psno" >1</td>
    <td><div id="PproductName" contenteditable>Product/Service</td>
    <td><div id="PHSN" contenteditable></td>
    <td><div id="PUOM" contenteditable>BOXES</td>
    <td><div id="PQty" contenteditable>6</td>
    <td><div id="PRate" contenteditable>6.10</td>
    <td><div id="PAmount">--</td>
  </tr>
</table>

<button id="AddTable">Add Row with ID</button>

的JavaScript

var count = 0;

$("#AddTable").click(function() {

    count ++;

    var html = "<tr><td><div id=\"RowId_" + count + "\">" + count + "</div></td><td><div contenteditable></div></td><td><div contenteditable></div></td><td><div contenteditable></div></td><td><div contenteditable></div></td><td><div contenteditable></div></td><td><div contenteditable></div></td><td><div contenteditable></div></td></tr>";

  $("#billTable").append(html);
});

https://jsfiddle.net/g2d8L749/

请告诉我这是你的想法吗?

答案 1 :(得分:0)

如果您正在寻找最简单的解决方案,我建议使用tableTOJSON插件。

(function( $ ) {
  'use strict';

  $.fn.tableToJSON = function(opts) {

    // Set options
    var defaults = {
      ignoreColumns: [],
      onlyColumns: null,
      ignoreHiddenRows: true,
      ignoreEmptyRows: false,
      headings: null,
      allowHTML: false,
      includeRowId: false,
      textDataOverride: 'data-override',
      extractor: null,
      textExtractor: null
    };
    opts = $.extend(defaults, opts);

    var notNull = function(value) {
      return value !== undefined && value !== null;
    };

    var notEmpty = function(value) {
      return value !== undefined && value.length > 0;
    };

    var ignoredColumn = function(index) {
      if( notNull(opts.onlyColumns) ) {
        return $.inArray(index, opts.onlyColumns) === -1;
      }
      return $.inArray(index, opts.ignoreColumns) !== -1;
    };

    var arraysToHash = function(keys, values) {
      var result = {}, index = 0;
      $.each(values, function(i, value) {
        // when ignoring columns, the header option still starts
        // with the first defined column
        if ( index < keys.length && notNull(value) ) {
          if (notEmpty(keys[index])){
            result[ keys[index] ] = value;
          }
          index++;
        }
      });
      return result;
    };

    var cellValues = function(cellIndex, cell, isHeader) {
      var $cell = $(cell),
        // extractor
        extractor = opts.extractor || opts.textExtractor,
        override = $cell.attr(opts.textDataOverride),
        value;
      // don't use extractor for header cells
      if ( extractor === null || isHeader ) {
        return $.trim( override || ( opts.allowHTML ? $cell.html() : cell.textContent || $cell.text() ) || '' );
      } else {
        // overall extractor function
        if ( $.isFunction(extractor) ) {
          value = override || extractor(cellIndex, $cell);
          return typeof value === 'string' ? $.trim( value ) : value;
        } else if ( typeof extractor === 'object' && $.isFunction( extractor[cellIndex] ) ) {
          value = override || extractor[cellIndex](cellIndex, $cell);
          return typeof value === 'string' ? $.trim( value ) : value;
        }
      }
      // fallback
      return $.trim( override || ( opts.allowHTML ? $cell.html() : cell.textContent || $cell.text() ) || '' );
    };

    var rowValues = function(row, isHeader) {
      var result = [];
      var includeRowId = opts.includeRowId;
      var useRowId = (typeof includeRowId === 'boolean') ? includeRowId : (typeof includeRowId === 'string') ? true : false;
      var rowIdName = (typeof includeRowId === 'string') === true ? includeRowId : 'rowId';
      if (useRowId) {
        if (typeof $(row).attr('id') === 'undefined') {
          result.push(rowIdName);
        }
      }
      $(row).children('td,th').each(function(cellIndex, cell) {
        result.push( cellValues(cellIndex, cell, isHeader) );
      });
      return result;
    };

    var getHeadings = function(table) {
      var firstRow = table.find('tr:first').first();
      return notNull(opts.headings) ? opts.headings : rowValues(firstRow, true);
    };

    var construct = function(table, headings) {
      var i, j, len, len2, txt, $row, $cell,
        tmpArray = [], cellIndex = 0, result = [];
      table.children('tbody,*').children('tr').each(function(rowIndex, row) {
        if( rowIndex > 0 || notNull(opts.headings) ) {
          var includeRowId = opts.includeRowId;
          var useRowId = (typeof includeRowId === 'boolean') ? includeRowId : (typeof includeRowId === 'string') ? true : false;

          $row = $(row);

          var isEmpty = ($row.find('td').length === $row.find('td:empty').length) ? true : false;

          if( ( $row.is(':visible') || !opts.ignoreHiddenRows ) && ( !isEmpty || !opts.ignoreEmptyRows ) && ( !$row.data('ignore') || $row.data('ignore') === 'false' ) ) {
            cellIndex = 0;
            if (!tmpArray[rowIndex]) {
              tmpArray[rowIndex] = [];
            }
            if (useRowId) {
              cellIndex = cellIndex + 1;
              if (typeof $row.attr('id') !== 'undefined') {
                tmpArray[rowIndex].push($row.attr('id'));
              } else {
                tmpArray[rowIndex].push('');
              }
            }

            $row.children().each(function(){
              $cell = $(this);
              // skip column if already defined
              while (tmpArray[rowIndex][cellIndex]) { cellIndex++; }

              // process rowspans
              if ($cell.filter('[rowspan]').length) {
                len = parseInt( $cell.attr('rowspan'), 10) - 1;
                txt = cellValues(cellIndex, $cell);
                for (i = 1; i <= len; i++) {
                  if (!tmpArray[rowIndex + i]) { tmpArray[rowIndex + i] = []; }
                  tmpArray[rowIndex + i][cellIndex] = txt;
                }
              }
              // process colspans
              if ($cell.filter('[colspan]').length) {
                len = parseInt( $cell.attr('colspan'), 10) - 1;
                txt = cellValues(cellIndex, $cell);
                for (i = 1; i <= len; i++) {
                  // cell has both col and row spans
                  if ($cell.filter('[rowspan]').length) {
                    len2 = parseInt( $cell.attr('rowspan'), 10);
                    for (j = 0; j < len2; j++) {
                      tmpArray[rowIndex + j][cellIndex + i] = txt;
                    }
                  } else {
                    tmpArray[rowIndex][cellIndex + i] = txt;
                  }
                }
              }

              txt = tmpArray[rowIndex][cellIndex] || cellValues(cellIndex, $cell);
              if (notNull(txt)) {
                tmpArray[rowIndex][cellIndex] = txt;
              }
              cellIndex++;
            });
          }
        }
      });
      $.each(tmpArray, function( i, row ){
        if (notNull(row)) {
          // remove ignoredColumns / add onlyColumns
          var newRow = notNull(opts.onlyColumns) || opts.ignoreColumns.length ?
            $.grep(row, function(v, index){ return !ignoredColumn(index); }) : row,

            // remove ignoredColumns / add onlyColumns if headings is not defined
            newHeadings = notNull(opts.headings) ? headings :
              $.grep(headings, function(v, index){ return !ignoredColumn(index); });

          txt = arraysToHash(newHeadings, newRow);
          result[result.length] = txt;
        }
      });
      return result;
    };

    // Run
    var headings = getHeadings(this);
    return construct(this, headings);
  };
})( jQuery );

将其复制到单独的js文件中。将其保存为.js,然后调用$("#your_table_id").tableTOJSON();

例如:

var data = $("#your_table_id").tableTOJSON();
var table_data = {'table_data':data};
console.log(data); //gives you json data now you can play with you data

现在您可以通过为您的表提供ID而无需其他ID来获取JSON ... 希望这可以帮助!!干杯!!