add dynamic rows to a table with data from another table

2

Good morning, I need help to do the following: I need that from a modal with a table of data (extracted from my database), they are added to another table, dynamically. This is the design of my modal, showing information from my database:

And this is the code with which I show the data: 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>

I want that from the add button that is generated for each row, I can add the data of that row to this other table:

But that can only be added once per row. Besides that at the same time I would like that within this table an input text is generated to indicate the quantity of said product and the delete button to get rid of that row. Something like this:

I have started looking in several places, but I can not find anything about what I need. I want to avoid the possible use of libraries, because I'm just starting with this of web programming, and I think that using libraries at the level that I am, would be something harmful to my learning. Thanks in advance.

    
asked by Raphael 19.06.2016 в 15:53
source

1 answer

2

The steps are the following:

  • You get the row to which the button belongs, you do it by means of the parentNode property or by parent() if you use jQuery.
  • Extras the cells (td) of that row (only the values you will use).
  • You create a cell for each value extracted and put that same value in the new cell of the target table.
  • You create a cell and create the <input type="number" ... /> for the amount. You add the input to the cell.
  • Create a cell and create the <button ...>Descartar</button> to discard that product. You add the button to the cell.
  • You add the cells to a new row, and that row to <tbody> of the target table.
  • 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>

    With jQuery it's much simpler still:

    Instead of using document.createElement , you only use the append method and pass as string the element to add. For example:

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

    And to discard a product:

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

    Update the price as the amount changes

    To update the price as the amount is increased / decreased, it is necessary to place a listener per event change to the quantity input. Also, for reasons of convenience, we keep the price of the product in a data-price attribute every time we add a row to the destination table.

    In the new row we add:

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

    To the% co_of% of quantity we add the listener:

    inputQty.onchange = onQtyChange;
    

    And the listener for the change event:

    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;
    }
    

    Result

    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>
        
    answered by 19.06.2016 / 16:52
    source