добавление динамических строк в таблицу с данными из другой таблицы


Хорошо, мне нужна помощь, чтобы я мог выполнить следующее: Мне нужно, чтобы из модального с таблицей данных(извлеченных из моей базы данных) они были добавлены в другую таблицу динамически. Это мой модальный дизайн, отображающий информацию из моей базы данных:

introducir la descripción de la imagen aquí

и это код, с помощью которого я показываю данные: venta_venta.php

<?php 
require_once('php/conexion.php');

    # code...
// PARA OBTENER LOS DATAS DE LA TABLA CLIENTE ====================
    $sql = "SELECT * FROM cliente";
    $result = $conn->query($sql);
 // PARA OBTENER LOS DATAS DE LA TABLA PRODUCTO====================
    $sql2="SELECT * FROM producto";
    $result2=$conn->query($sql2);
?>

<table class="table table-bordered table-hover">
              <thead>
                 <tr>

                   <th>Articulo</th>
                   <th>Unidad M.</th>
                   <th>Valor</th>
                   <th>Categoria</th>
                   <th>P.Unitario</th>
                   <th>Imagen</th>
                   <th>Accion</th>
                 </tr>
                </thead>
                <tbody>


            <?php 
                if ($result2->num_rows > 0) {
                    // output data of each row
                    while($row = $result2->fetch_assoc()) {

                echo '<tr><td>'.$row["nombre"].'</td><td>'.$row["unidad_medida"].'</td><td>'.$row["peso"].'</td><td>'.$row["categoria"].'</td><td>'.$row["precio"].'</td><td><img height="100" width="100" src="php/'.$row["imagen"].'" alt="img01" /></td><td><button type="button" class="btn btn-primary" id="idagregar" data-dismiss="modal"><i class="fa fa-plus" ></i>&nbsp;Agregar</button></td></tr>';

                    }
                } else {
                    echo "0 results";
                }

                $conn->close();

            ?>
           </tbody>
  </table>

я хочу, чтобы из кнопки Add, которая генерируется каждой строкой, я мог добавить данные из этой строки в эту другую таблицу:

introducir la descripción de la imagen aquí

но он может быть добавлен только один раз для каждой строки. Кроме того, в то же время я хотел бы, чтобы внутри этой таблицы был сгенерирован input text, чтобы указать количество такого продукта и кнопку Delete, чтобы избавиться от этой строки. Что-то вроде этого:

introducir la descripción de la imagen aquí

я начал искать с разных сторон, но я не могу найти ничего относительно того, что мне нужно. Я хочу избежать возможного использование библиотек, потому что я только начинаю с этого веб-программирования, и я думаю, что использование библиотек на том уровне, на котором я нахожусь, будет чем-то вредным для моего обучения. Заранее спасибо.

Author: Raphael, 2016-06-19

1 answers

Шаги следующие:

  1. вы получаете строку, к которой принадлежит кнопка, вы делаете это с помощью свойства parentNode или с помощью parent() Если вы используете jQuery.
  2. дополнительно ячейки (td) этой строки (только значения, которые вы будете использовать).
  3. вы создаете одну ячейку для каждого извлеченного значения и помещаете это же значение в новую ячейку целевой таблицы.
  4. вы создаете ячейку и создаете <input type="number" ... /> Для количества. Вы добавляете input в ячейку.
  5. ячейка и вы создаете <button ...>Descartar</button>, чтобы отбросить этот продукт. Вы добавляете кнопку в ячейку.
  6. вы добавляете ячейки в новую строку и эту строку в <tbody> целевой таблицы.

function add(button) {
	var row = button.parentNode.parentNode;
  var cells = row.querySelectorAll('td:not(:last-of-type)');
  addToCartTable(cells);
}

function remove() {
	var row = this.parentNode.parentNode;
    document.querySelector('#target tbody')
            .removeChild(row);
}

function addToCartTable(cells) {
   var code = cells[1].innerText;
   var name = cells[2].innerText;
   var price = cells[3].innerText;
   
   var newRow = document.createElement('tr');
   
   newRow.appendChild(createCell(code));
   newRow.appendChild(createCell(name));
   newRow.appendChild(createCell(price));
   var cellInputQty = createCell();
   cellInputQty.appendChild(createInputQty());
   newRow.appendChild(cellInputQty);
   var cellRemoveBtn = createCell();
   cellRemoveBtn.appendChild(createRemoveBtn())
   newRow.appendChild(cellRemoveBtn);
   
   document.querySelector('#target tbody').appendChild(newRow);
}

function createInputQty() {
	var inputQty = document.createElement('input');
  inputQty.type = 'number';
  inputQty.required = 'true';
  inputQty.min = 1;
  inputQty.className = 'form-control'
  return inputQty;
}

function createRemoveBtn() {
	var btnRemove = document.createElement('button');
  btnRemove.className = 'btn btn-xs btn-danger';
  btnRemove.onclick = remove;
  btnRemove.innerText = 'Descartar';
  return btnRemove;
}

function createCell(text) {
	var td = document.createElement('td');
  if(text) {
  	td.innerText = text;
  }
  return td;
}
*, *:before, *:after {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}
#target td {
  /* para centrado vertical de contenido */
  vertical-align: middle;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>
<div class="table-responsive">
<table id="source" class="table table-bordered table-hover">
  <thead>
    <tr>
      <th>#</th>
      <th>Código</th>
      <th>Nombre</th>
      <th>Precio</th>
      <th>Acciones</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>1</td>
      <td>C1483</td>
      <td>Laptop HP CX44</td>
      <td>$844.90</td>
      <td>
        <button onclick="add(this)" class="btn btn-primary btn-xs">
          Agregar
        </button>
      </td>
    </tr>
  </tbody>
</table>
</div>

<div class="table-responsive">
<table id="target" class="table table-bordered table-hover">
  <thead>
    <tr>
      <th>Código</th>
      <th>Nombre</th>
      <th>Precio</th>
      <th>Cantidad</th>
      <th>Acciones</th>
    </tr>
  </thead>
  <tbody>
  </tbody>
</table>
</div>

С jQuery это намного проще:

Вместо использования document.createElement вы просто используете метод append и передаете ему как string добавляемый элемент. Например:

$(newRow).append('<td>' + code + '</td>');

И отбросить продукт:

var row = $(this).parent().parent();
$('#target tbody').remove(row);

Обновить цену в соответствии с изменением количества

Чтобы обновить цену по мере увеличения / уменьшения количества, необходимо поместить прослушиватель для каждого события change в input количества. Кроме того, для удобства мы сохраняем цену продукта в атрибуте data-price каждый раз, когда добавляем строку в целевую таблицу.

В новую строку добавляем:

newRow.setAttribute('data-price', price.substring(1));

К <input /> количества мы добавляем слушатель:

inputQty.onchange = onQtyChange;

И прослушиватель для события изменения:

function onQtyChange(e) {
  var row = this.parentNode.parentNode;
    var cellPrice = row.querySelector('td:nth-child(3)');
  var prevPrice = Number(row.getAttribute('data-price'));
  var newQty = Number(this.value);
  var total = prevPrice * newQty;
  cellPrice.innerText = '$' + total;
}

Результат

function add(button) {
	var row = button.parentNode.parentNode;
  var cells = row.querySelectorAll('td:not(:last-of-type)');
  addToCartTable(cells);
}

function remove() {
	var row = this.parentNode.parentNode;
  document.querySelector('#target tbody')
  				.removeChild(row);
}

function addToCartTable(cells) {
   var code = cells[1].innerText;
   var name = cells[2].innerText;
   var price = cells[3].innerText;
   
   var newRow = document.createElement('tr');
   newRow.setAttribute('data-price', price.substring(1));
   
   newRow.appendChild(createCell(code));
   newRow.appendChild(createCell(name));
   newRow.appendChild(createCell(price));
   var cellInputQty = createCell();
   cellInputQty.appendChild(createInputQty());
   newRow.appendChild(cellInputQty);
   var cellRemoveBtn = createCell();
   cellRemoveBtn.appendChild(createRemoveBtn())
   newRow.appendChild(cellRemoveBtn);
   
   document.querySelector('#target tbody').appendChild(newRow);
}

function createInputQty() {
	var inputQty = document.createElement('input');
  inputQty.type = 'number';
  inputQty.required = 'true';
  inputQty.className = 'form-control'
  inputQty.min = 1; // mínimo un producto
  inputQty.onchange = onQtyChange;
  return inputQty;
}

function createRemoveBtn() {
	var btnRemove = document.createElement('button');
  btnRemove.className = 'btn btn-xs btn-danger';
  btnRemove.onclick = remove;
  btnRemove.innerText = 'Descartar';
  return btnRemove;
}

function createCell(text) {
	var td = document.createElement('td');
  if(text) {
  	td.innerText = text;
  }
  return td;
}

function onQtyChange(e) {
  var row = this.parentNode.parentNode;
	var cellPrice = row.querySelector('td:nth-child(3)');
  var prevPrice = Number(row.getAttribute('data-price'));
  var newQty = Number(this.value);
  var total = prevPrice * newQty;
  cellPrice.innerText = '$' + total;
}
*, *:before, *:after {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}
#target td {
  /* para centrado vertical de contenido */
  vertical-align: middle;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>
<div class="table-responsive">
<table id="source" class="table table-bordered table-hover">
  <thead>
    <tr>
      <th>#</th>
      <th>Código</th>
      <th>Nombre</th>
      <th>Precio</th>
      <th>Acciones</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>1</td>
      <td>C1483</td>
      <td>Laptop HP CX44</td>
      <td>$844.90</td>
      <td>
        <button onclick="add(this)" class="btn btn-primary btn-xs">
          Agregar
        </button>
      </td>
    </tr>
  </tbody>
</table>
</div>

<div class="table-responsive">
<table id="target" class="table table-bordered table-hover">
  <thead>
    <tr>
      <th>Código</th>
      <th>Nombre</th>
      <th>Precio</th>
      <th>Cantidad</th>
      <th>Acciones</th>
    </tr>
  </thead>
  <tbody>
  </tbody>
</table>
</div>
 2
Author: gugadev, 2016-06-19 15:10:13