1

Estoy haciendo un crud con JSON y Javascript, todo esto a base de LocalStorage, alguien me puede brindar ayuda ya que no puedo realizar la eliminación de una fila con un producto en si.

window.onload = function () {

    var arc = new XMLHttpRequest();
    arc.open("GET", "./doc/productos.json");
    arc.onload = function () {
        if (arc.status == 200) {
            var productos = JSON.parse(arc.responseText);
            console.log(productos);
            document.getElementById("codProd").onblur = function () {
                var codigo = document.getElementById("codProd").value;

                for (var i = 0; i < productos.length; i++) {
                    if (productos[i].Codigo == codigo) {
                        document.getElementById("desProd").value = productos[i].Nombre;
                        document.getElementById("preProd").value = productos[i].Valor;
                    }
                }
            };

            document.getElementById("canProd").onblur = function () {
                var cantidad = document.getElementById("canProd").value;

                for (var i = 0; i < productos.length; i++) {
                    if (productos[i] > cantidad) {
                        var valor = document.getElementById("preProd").value;

                        var subtotal = valor * cantidad;
                        document.getElementById("stProd").value = subtotal;
                    }
                }
            };



            //AGREGAR COLUMNA PARA BOTON ELIMINAR

            function agregarColumna(colCount) {
                var table = document.getElementById('lista');
                var rowCount = table.rows.length;
                for (var i = 0; i < rowCount; i++) {
                    var row = table.rows[i];
                    row.insertCell(colCount);

                    //AGREGAR PRODUCTOS A LOCALSTORAGE

                    var pCodigo = [],
                            pDescripcion = [],
                            pPrecio = [],
                            pCantidad = [],
                            pSubtotal = [];

                    if (localStorage.getItem('codigo_producto') != null) {
                        pCodigo = JSON.parse(localStorage.getItem('codigo_producto'));
                        pDescripcion = JSON.parse(localStorage.getItem('descripcion_producto'));
                        pPrecio = JSON.parse(localStorage.getItem('precio_producto'));
                        pCantidad = JSON.parse(localStorage.getItem('cantidad_producto'));
                        pSubtotal = JSON.parse(localStorage.getItem('subtotal_producto'));
                    }

                    var agregarProducto = document.querySelector('#btnAgregar');

                    agregarProducto.addEventListener('click', registrarProducto);

                    function registrarProducto() {
                        var codigo = document.querySelector('#codProd').value,
                                descripcion = document.querySelector('#desProd').value,
                                precio = document.querySelector('#preProd').value,
                                cantidad = document.querySelector('#canProd').value,
                                subtotal = document.querySelector('#stProd').value;

                        pCodigo.push(codigo);
                        pDescripcion.push(descripcion);
                        pPrecio.push(precio);
                        pCantidad.push(cantidad);
                        pSubtotal.push(subtotal);

                        localStorage.setItem('codigo_producto', JSON.stringify(pCodigo));
                        localStorage.setItem('descripcion_producto', JSON.stringify(pDescripcion));
                        localStorage.setItem('precio_producto', JSON.stringify(pPrecio));
                        localStorage.setItem('cantidad_producto', JSON.stringify(pCantidad));
                        localStorage.setItem('subtotal_producto', JSON.stringify(pSubtotal));

                        llenarTabla();

                    }

                    //MOSTRAR PRODUCTOS DE LOCALSTORAGE

                    llenarTabla();

                    function llenarTabla() {
                        var tbody = document.querySelector('#lista tbody');
                        tbody.innerHTML = '';

                        var pCodigo = JSON.parse(localStorage.getItem('codigo_producto')),
                                pDescripcion = JSON.parse(localStorage.getItem('descripcion_producto')),
                                pPrecio = JSON.parse(localStorage.getItem('precio_producto')),
                                pCantidad = JSON.parse(localStorage.getItem('cantidad_producto')),
                                pSubtotal = JSON.parse(localStorage.getItem('subtotal_producto'));


                        var n = pCodigo.length;

                        for (var i = 0; i < n; i++) {
                            var fila = document.createElement('tr');

                            const button = document.createElement('button');
                            button.type = 'button';
                            button.innerText = 'Eliminar';
                            button.alt = 'Delete';
                            button.className = 'btnEliminar';
                            button.class = 'btnEliminar';
                            //button.setAttribute("onClick", "eliminarProducto(this)");
                            document.body.appendChild(button);

                            var celdaCod = document.createElement('td'),
                                    celdaDes = document.createElement('td'),
                                    celdaPre = document.createElement('td'),
                                    celdaCan = document.createElement('td'),
                                    celdaSub = document.createElement('td'),
                                    celdaEli = document.createElement('td');

                            var textoCod = document.createTextNode(pCodigo[i]),
                                    textoDes = document.createTextNode(pDescripcion[i]),
                                    textoPre = document.createTextNode(pPrecio[i]),
                                    textoCan = document.createTextNode(pCantidad[i]),
                                    textoSub = document.createTextNode(pSubtotal[i]);


                            celdaCod.appendChild(textoCod);
                            celdaDes.appendChild(textoDes);
                            celdaPre.appendChild(textoPre);
                            celdaCan.appendChild(textoCan);
                            celdaSub.appendChild(textoSub);
                            celdaEli.appendChild(button);

                            fila.appendChild(celdaCod);
                            fila.appendChild(celdaDes);
                            fila.appendChild(celdaPre);
                            fila.appendChild(celdaCan);
                            fila.appendChild(celdaSub);
                            fila.appendChild(celdaEli);

                            tbody.appendChild(fila);

                        }
                    }
                }

            }
            agregarColumna();

            var total = document.getElementById("total");
            total.hidden = false;

            const button = document.createElement('button');
            button.type = 'button';
            button.innerText = 'Pagar';
            button.setAttribute("onclick", "pagar(this)");
            document.body.appendChild(button);

            var monto = 10000;
            total.innerHTML = monto;

        }
    };

    arc.send();
};
body {
    font-family: arial;
}

label {
    display: inline-block;
}

table {
    width: 100%;
}

thead {
    background-color: lightskyblue;
}
<!DOCTYPE html>
<html>
    <head>
        <title>Tienda</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link href="css/estilos.css" rel="stylesheet" type="text/css"/>
    </head>
    <body>
        <h1>Productos</h1>
        <div id="contenedor">
            <label>Codigo Producto<br><input type="text" id="codProd"/></label>
            <label>Descripción<br><input type="text" id="desProd"/></label>
            <label>Precio Unitario<br><input type="text" id="preProd"/></label>
            <label>Cantidad<br><input type="text" id="canProd"/></label>            
            <label>Subtotal<br><input type="text" id="stProd"/></label>            
            <label><button id="btnAgregar">Agregar</button></label>
        </div>
        <h3>Productos seleccionados</h3>
        <table id="lista"> 
            <thead>
                <tr>
                    <th>Código</th>
                    <th>Descripción</th>
                    <th>P. Unitario</th>
                    <th>Cantidad</th>
                    <th>Subtotal</th>
                </tr>
            </thead>
            <tbody>                
            </tbody>
        </table>        
        <div id="total" hidden="">
            <h3>Total a pagar</h3>
        </div>
        <script src="js/acciones.js" type="text/javascript"></script>
    </body>
</html>


Este es el archivo JSON:

[
  {
    "Codigo": "1101",
    "Nombre": "Computador IBM",
    "Valor": "375000"
  },
  {
    "Codigo": "1102",
    "Nombre": "Computador HP",
    "Valor": "468000"
  },
  {
    "Codigo": "1103",
    "Nombre": "Computador MAC",
    "Valor": "1200000"
  },
  {
    "Codigo": "2201",
    "Nombre": "Celular Alcatel",
    "Valor": "65000"
  },
  {
    "Codigo": "2202",
    "Nombre": "Celular Nokia",
    "Valor": "75000"
  }
]
1
  • Creo que el problema principal es que estás haciendo la lectura a un archivo JSON y también trabajando con LocalStorage, deberías tener el JSON almacenado desde el inicio en localStorage y todo realizarlo ahí. el 5 dic. 2019 a las 16:09

0

Tu Respuesta

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

Examina otras preguntas con la etiqueta o formula tu propia pregunta.