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));
displayCart();
}
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;
}
Ok, there’s usually a way to do it. Something like
$('#MyForm')[0].reset();
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).