How to clear data after submit the form?

I am playing with the JS shopping cart, when I submit the form, the content is stick in the form field, how can I empty the form field. Here is my code below:

var inames = [];
    var iqtyp = [];
    var iprice = [];

    function additem(){
        var names = inames.push(document.getElementById('pname').value);
        var qty = iqtyp.push(parseInt(document.getElementById('pqty').value));
        var price = iprice.push(parseInt(document.getElementById('price').value));


    function displayCart(){
        cartData = "<table><tr><th>Product Name</th><th>Quantity</th><th>Price</th><th>Total</th></tr>";

        var total = 0;

        for(i = 0; i < inames.length; i++){
            total += iqtyp[i] * iprice[i];
            cartData += "<tr><td>" + inames[i] + "</td><td>" + iqtyp[i] + "</td><td>" + iprice[i] + "</td><td>" + iqtyp[i] * iprice[i] + "</td><td><button onclick='delElement(" + i + ")'>Delete</button></td></tr>"

        cartData += '<tr><td></td><td></td><td></td><td>' + total + '</td></tr></table>';

        document.getElementById('cart').innerHTML = cartData;



Does the form have a class or id?

Hi, the form native reset method will probably help:

yes, this is the html code

<div id="frm">
    <label>Product Name</label>
    <input id="pname" type="text"><br>
    <input id="pqty" type="number"><br>
    <label>Unit Price</label>
    <input type="number" id="price"><br>
    <button onclick='additem()'>Add item</button>

<div id="cart"></div>

Ok, there’s usually a way to do it. Something like


It should reset everything, but I’m not entirely sure it’ll work because this is with Jquery which I’m not sure you are using. I think what @Andres_Vaquero has posted is another way to do it via Javascript.

I also don’t see where you are submitting the form though since there is no actual form you’ve provided except a reference to it via a button.

Maybe that’s the problem. If there was a form, submitting it would send a request the action URI – keeping the form and its input values would actually require some extra effort (such as using AJAX or re-populating the form on the server side).


There is no form but now I have created the form and use the reset() function to do the job.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.