简体   繁体   中英

I want to add products to table but when i add new proudct its quantity and subtotal gets refreshed (by default 1 ) using Javascript

I want to add products to table but when i add new proudct its quantity and subtotal gets refreshed (by default 1 ) using Javascript. How do i add product without getting old data refreshed?? Should I store product data into local storage instead.

Image is given below to better understand my problem...

 let product_name = '' let product_price = '' let quantity = 1 const quantity_change = (x) => { x.parentElement.parentNode.children[3].children[0].value = x.value * product_price } const deleteRow = (row) => { row.parentElement.parentElement.remove() } const getProduct = (x) => { product_name = x.children[2].value product_price = x.children[2].value product_subtotal = parseInt(quantity) * parseInt(product_price); let tbody = document.getElementById("tbody").innerHTML += ` <tr> <td>${product_name}</td> <td><input type='number' onchange='quantity_change(this)' value='${quantity}' class='form-control'</td> <td><input type='text' value='${product_price}' class='form-control' readonly/></td> <td><input type='text' value='${product_price * quantity}' class='form-control' readonly/></td> <td><button class='btn btn-danger' onclick="deleteRow(this)">x</button></td> </tr> ` }
 <table class="table "> <tr> <th>Product Name</th> <th>Quantity</th> <th>Price</th> <th>Subtotal</th> <th>X</th> </tr> <tbody id="tbody"> </tbody> </table>

I solved the problem using following code. I used built in JavaScript table functions .

const getProduct = (x) =>
{
    product_name = x.children[1].value
    product_price = x.children[2].value
    product_subtotal = parseInt(quantity) * parseInt(product_price);

    let tbody = document.getElementById("tbody");
    let row = tbody.insertRow(tbody)
    let cell1 = row.insertCell(0);
    let cell2 = row.insertCell(1);
    let cell3 = row.insertCell(2);
    let cell4 = row.insertCell(3);
    let cell5 = row.insertCell(4);

    cell1.innerHTML = `${product_name}`
    cell2.innerHTML = `<input type='number' onclick='quantity_change(this)' value='${quantity}' class='form-control'/>`
    cell3.innerHTML = `<input type='text' value='${product_price}' class='form-control' readonly/>`
    cell4.innerHTML = `<input type='text' value='${product_price * quantity}' class='form-control' readonly/>`
    cell5.innerHTML = `<button class='btn btn-danger' onclick="deleteRow(this)">x</button>`

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM