1

The first question is I need help in delete function. I already tried the splice method but I still can't get it. When you click the delete item button, that row must be deleted. The second question has ii already put the required attribute in the input form but it still submits the form when the field is empty.

var qtyTotal = 0;
    var priceTotal = 0;
    var products = [];


    function addProduct() {
        var productID = document.getElementById("productID").value;
        var product_desc = document.getElementById("product_desc").value;
        var qty = document.getElementById("quantity").value;
        // qtyTotal = qtyTotal + parseInt(qty);
        //document.getElementById("qtyTotals").innerHTML=qtyTotal;
        var price = document.getElementById("price").value;

      var newProduct = {

          product_id : null,
          product_desc : null,
          product_qty : 0,
          product_price : 0.00,
      };
        newProduct.product_id = productID;
        newProduct.product_desc = product_desc;
        newProduct.product_qty = qty;
        newProduct.product_price = price;
        

        products.push(newProduct);

        //console.log("New Product " + JSON.stringify(newProduct))
        //console.log("Products " + JSON.stringify(products))

        var html = "<table border='1|1' >";
        html+="<td>Product ID</td>";
        html+="<td>Product Description</td>";
        html+="<td>Quantity</td>";
        html+="<td>Price</td>";
        html+="<td>Action</td>";
        for (var i = 0; i < products.length; i++) {
        html+="<tr>";
        html+="<td>"+products[i].product_id+"</td>";
        html+="<td>"+products[i].product_desc+"</td>";
        html+="<td>"+products[i].product_qty+"</td>";
        html+="<td>"+products[i].product_price+"</td>";
        html+="<td><button type='submit' onClick='deleteProduct();'/>Delete Item</button> &nbsp <button type='submit' onClick='addCart();'/>Add to Cart</button></td>";
        html+="</tr>";
    }
        html+="</table>";
        document.getElementById("demo").innerHTML = html;

        document.getElementById("resetbtn").click()            
}
    function deleteProduct(product_id) {
    for(var i = 0; i < products.length; i++) {
        if (products[i].product_id == product_id) {
            // DO NOT CHANGE THE 1 HERE
            products.splice(i, 1);
        }
    }
}
<!DOCTYPE html>
<html>
<head>
    <title>Shopping Cart Pure Javascript</title>
</head>

<body>
<form name="order" id="order">
    <table>
        <tr>
            <td>
                <label for="productID">Product ID:</label>
            </td>
            <td>
                <input id="productID" name="product" type="text" size="28" required/>
            </td>
        </tr>
        <tr>
            <td>
                <label for="product">Product Desc:</label>
            </td>
            <td>
                <input id="product_desc" name="product" type="text" size="28" required/>
            </td>
        </tr>
        <tr>
            <td>
                <label for="quantity">Quantity:</label>
            </td>
            <td>
                <input id="quantity" name="quantity" width="196px" required/>
            </td>
        </tr>
        <tr>
            <td>
                <label for="price">Price:</label>
            </td>
            <td>
                <input id="price" name="price" size="28" required/>
            </td>
        </tr>
    </table>
    <input type="reset" name="reset" id="resetbtn" class="resetbtn" value="Reset" />
    <input type="button" id="btnAddProduct" onclick="addProduct();" value="Add New Product" >


</form>
<br>

<p id="demo"></p>
</body>
</html>

3
  • 1
    "i already put the required attribute in the input form but it still submits the form when the field is empty" - How are you submitting the form? Looks like your form element doesn't contain any submit buttons, and the submit buttons that you create dynamically are added to an element outside the form. Commented Jun 28, 2017 at 3:36
  • @nnnnnn—forms can be submitted by pressing enter with the focus on an input element. A feature often forgotten in forms submitted programatically. :-( Commented Jun 28, 2017 at 3:45
  • @RobG - I thought that only applied to forms with a single input element? Commented Jun 28, 2017 at 3:48

5 Answers 5

2

Firstly, you will have to pass correct product_id to delete function. Also you need to know which element to remove, for this you can send the current element on which click is pressed and then access its parent node to remove it. You can replace your script with following code:

var qtyTotal = 0;
    var priceTotal = 0;
    var products = [];


    function addProduct() {
        var productID = document.getElementById("productID").value;
        var product_desc = document.getElementById("product_desc").value;
        var qty = document.getElementById("quantity").value;
        // qtyTotal = qtyTotal + parseInt(qty);
        //document.getElementById("qtyTotals").innerHTML=qtyTotal;
        var price = document.getElementById("price").value;

      var newProduct = {

          product_id : null,
          product_desc : null,
          product_qty : 0,
          product_price : 0.00,
      };
        newProduct.product_id = productID;
        newProduct.product_desc = product_desc;
        newProduct.product_qty = qty;
        newProduct.product_price = price;


        products.push(newProduct);

        //console.log("New Product " + JSON.stringify(newProduct))
        //console.log("Products " + JSON.stringify(products))

        var html = "<table id='products-table' border='1|1' >";
        html+="<td>Product ID</td>";
        html+="<td>Product Description</td>";
        html+="<td>Quantity</td>";
        html+="<td>Price</td>";
        html+="<td>Action</td>";
        for (var i = 0; i < products.length; i++) {
        html+="<tr>";
        html+="<td>"+products[i].product_id+"</td>";
        html+="<td>"+products[i].product_desc+"</td>";
        html+="<td>"+products[i].product_qty+"</td>";
        html+="<td>"+products[i].product_price+"</td>";
        html+="<td><button type='submit' onClick='deleteProduct(\""+products[i].product_id +"\", this);'/>Delete Item</button> &nbsp <button type='submit' onClick='addCart();'/>Add to Cart</button></td>";
        html+="</tr>";
    }
        html+="</table>";
        document.getElementById("demo").innerHTML = html;

        document.getElementById("resetbtn").click()            
}
    function deleteProduct(product_id, e) {

    var pTbody = e.parentNode.parentNode.parentNode;
var pTable = pTbody.parentNode;
if((pTbody.children).length === 2)
    pTable.parentNode.removeChild(pTable);
else
    pTbody.removeChild(e.parentNode.parentNode);


    for(var i = 0; i < products.length; i++) {
        if (products[i].product_id == product_id) {
            // DO NOT CHANGE THE 1 HERE
            products.splice(i, 1);
        }
    }
}
Sign up to request clarification or add additional context in comments.

6 Comments

First, add the field with whatever value you want. Second add the field without any value. Then delete the second one that youve added, then delete the first. The first one is still there
@charles sorry i missed that, it is correct now i suppose.
Thank you sir. It works now. By the way, how not to add to the table if the value is blank?
@charles I have made changes script now removes table if the table is empty.
yes it's working now. But i have another question. How not to add to table if value is empty. It alerts user if entered value is empty. Thanks Diwas
|
1

Your main problem is that you're not passing the product id to the delete function, and you are expecting it on it.

Also, you can remove the HTML element itself.

I've done this snippet. I've added the product id as a the id for the row element of the table, so on your delete function you can remove it looking for that id.

Also, if the item to delete is the last on the table, the table will be removed too (I've added an id to the table so you can easily remove it)

var qtyTotal = 0;
var priceTotal = 0;
var products = [];

function addProduct() {
    var productID = document.getElementById("productID").value;
    var product_desc = document.getElementById("product_desc").value;
    var qty = document.getElementById("quantity").value;
    // qtyTotal = qtyTotal + parseInt(qty);
    //document.getElementById("qtyTotals").innerHTML=qtyTotal;
    var price = document.getElementById("price").value;

    var newProduct = {
      product_id : null,
      product_desc : null,
      product_qty : 0,
      product_price : 0.00,
    };
    
    newProduct.product_id = productID;
    newProduct.product_desc = product_desc;
    newProduct.product_qty = qty;
    newProduct.product_price = price;


    products.push(newProduct);

    //console.log("New Product " + JSON.stringify(newProduct))
    //console.log("Products " + JSON.stringify(products))

    var html = "<table id='products-table' border='1|1' >";
    html+="<td>Product ID</td>";
    html+="<td>Product Description</td>";
    html+="<td>Quantity</td>";
    html+="<td>Price</td>";
    html+="<td>Action</td>";
    for (var i = 0; i < products.length; i++) {
      html+="<tr id='"+products[i].product_id+"'>";
      html+="<td>"+products[i].product_id+"</td>";
      html+="<td>"+products[i].product_desc+"</td>";
      html+="<td>"+products[i].product_qty+"</td>";
      html+="<td>"+products[i].product_price+"</td>";
      html+="<td><button type='submit' onClick='deleteProduct("+products[i].product_id+");'/>Delete Item</button> &nbsp <button type='submit' onClick='addCart();'/>Add to Cart</button></td>";
      html+="</tr>";
    }
    
    html+="</table>";
    document.getElementById("demo").innerHTML = html;

    document.getElementById("resetbtn").click()            
}

function deleteProduct(product_id) {
    for(var i = 0; i < products.length; i++) {
        if (products[i].product_id == product_id) {
            // DO NOT CHANGE THE 1 HERE
            products.splice(i, 1);
            var element = document.getElementById(product_id);
            var tableElement = document.getElementById('products-table');
            
            if(!products.length)
              tableElement.parentNode.removeChild(tableElement);
            else
              tableElement.removeChild(element);
        }
    }
}
<!DOCTYPE html>
<html>
<head>
    <title>Shopping Cart Pure Javascript</title>
</head>

<body>
<form name="order" id="order">
    <table>
        <tr>
            <td>
                <label for="productID">Product ID:</label>
            </td>
            <td>
                <input id="productID" name="product" type="text" size="28" required/>
            </td>
        </tr>
        <tr>
            <td>
                <label for="product">Product Desc:</label>
            </td>
            <td>
                <input id="product_desc" name="product" type="text" size="28" required/>
            </td>
        </tr>
        <tr>
            <td>
                <label for="quantity">Quantity:</label>
            </td>
            <td>
                <input id="quantity" name="quantity" width="196px" required/>
            </td>
        </tr>
        <tr>
            <td>
                <label for="price">Price:</label>
            </td>
            <td>
                <input id="price" name="price" size="28" required/>
            </td>
        </tr>
    </table>
    <input type="reset" name="reset" id="resetbtn" class="resetbtn" value="Reset" />
    <input type="button" id="btnAddProduct" onclick="addProduct();" value="Add New Product" >


</form>
<br>

<p id="demo"></p>
</body>
</html>

Hope this helps!

7 Comments

This doesn't seem to delete rows when clicking Delete Item.
Have you run my snippet? it does delete rows when you click on Delete item
Ah, I did run it, however it relies on having an ID. I was adding rows without typing an ID. That's not a problem with your solution per se, more an issue with the OP's code not checking for an ID before adding the row. Upvoted.
yes, you are right... should check that the id has been inserted! but that is something else, as you said :)
sir, when there is no value(the table is blank) added, it can't be deleted.
|
1

The problem is that you are modifying the array of products without actually changing the HTML displayed on the page.

If you added code to delete the specified table element, I believe the problem would be solved.

For instance: You could attach an id that corresponds to product_id to each table when it's created, and then delete the table with that id.

var remove = document.getElementById(product_id);
remove.parentElement.removeChild(remove);

1 Comment

0

Your click handler is calling deleteProduct() which will call your function without passing a product_id value as a parameter so your if (products[i].product_id == product_id) will never evaluate to be true.

Try this:

 html+="<td><button type='submit' onClick='deleteProduct(\""+products[i].product_id +"\");'/>Delete Item</button> &nbsp; <button type='submit' onClick='addCart();'/>Add to Cart</button></td>";

As far as the required fields make sure you have the type attribute set on all of your inputs and move <p id="demo"></p> inside of your form.

2 Comments

You should format code as code. In this case I'd recommend using backticks ` around your code.
TY! Clonkex didn't know I could to that +1
0

You must change delete button type from submit to button and you must add products[i].product_id paramater for deleteProduct function

html+="<td><button type='button' onClick='deleteProduct("+products[i].product_id+");'/>Delete Item</button> &nbsp <button type='submit' onClick='addCart();'/>Add to Cart</button></td>";

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.