2

Buenas, necesito ayuda para poder realizar lo siguiente: Necesito que desde un modal con una tabla de datos(extraídas desde mi base de datos), se agreguen a otra tabla, dinamicamente. Este es el diseño de mi modal, mostrando información de mi base de datos:

introducir la descripción de la imagen aquí

Y este es el codigo con el cual muestro los datos: 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>

Quiero que desde el boton agregar que se genera por cada fila, pueda agregar los datos de esa fila a esta otra tabla:

introducir la descripción de la imagen aquí

Pero que solo se pueda agregar una vez por cada fila. Ademas de que al mismo tiempo me gustaría que dentro de esta tabla se genere un input text para indicar la cantidad de dicho producto y el boton eliminar para deshacerme de esa fila. Algo asi:

introducir la descripción de la imagen aquí

Me he puesto a buscar por varios lados, pero no encuentro nada referente a lo que necesito. Quiero evitar lo posible de usar librerias, porque recién estoy empezando con esto de la programacion web, y creo que usar librerias en el nivel que estoy, seria algo perjudicial para mi aprendizaje. Gracias de antemano.

1 respuesta 1

2

Los pasos son los siguientes:

  1. Obtienes la fila a la que pertenece el botón, lo haces por medio de la propiedad parentNode o por medio de parent() si usas jQuery.
  2. Extras las celdas (td) de esa fila (solo los valores que usarás).
  3. Creas una celda por cada valor extraído y pones ese mismo valor en la nueva celda de la tabla destino.
  4. Creas una celda y creas el <input type="number" ... /> para la cantidad. Agregas el input a la celda.
  5. Creas una celda y creas el <button ...>Descartar</button> para descartar ese producto. Agregas el botón a la celda.
  6. Agregas las celdas a una nueva fila, y esa fila al <tbody> de la tabla destino.

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>

Con jQuery es mucho más sencillo aún:

En lugar de hacer uso de document.createElement, solo haces uso del método append y le pasas como string el elemento a agregar. Por ejemplo:

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

Y para descartar un producto:

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

Actualizar el precio según cambie la cantidad

Para actualizar el precio según se aumente/disminuye la cantidad, es necesario colocar un escuchador por evento change al input de cantidad. Además, por razones de comodidad, guardamos el precio del producto en un atributo data-price cada vez que agregamos una fila a la tabla destino.

En la nueva fila añadimos:

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

Al <input /> de cantidad le añadimos el escuchador:

inputQty.onchange = onQtyChange;

Y el escuchador para el evento de cambio:

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

Resultado

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
  • Y para deshabilitar el boton de agregar después del primer click, como lo haría? Estoy intentando con el evento .one() de JQUERY, pero no me funciona. :/
    – Raphael
    el 19 jun. 2016 a las 23:43
  • 1
    En la función add agrega: button.disabled = true;
    – gugadev
    el 20 jun. 2016 a las 0:13

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.