So, I made two tables, one table has a form included in it, you will type whatever you want in that form, and then it will show in the other table.
<table>
<head>
<tr>
<th>Product Name</th>
<th>Product Price</th>
<th>Product Quantity</th>
<th>Product Barcode</th>
</tr>
</thead>
<tbody>
<tr>
<form id="input">
<td><input class="userinput" id="productname" type="text" placeholder="Product Name"></td>
<td><input class="userinput" id="productprice" type="text" placeholder="Product Price"></td>
<td><input class="userinput" id="productquantity" type="number" placeholder="Product Quantity"></td>
<td><input class="userinput" id="productcode" type="number" placeholder="Product Barcode"></td>
<td><button>Add Products</button></td>
</form>
</tr>
</tbody>
</table>
Users will enter data in this table and the data will show up in table 2 that is:
<table id="products">
<thead>
<tr>
<th>Product Name</th>
<th>Product Price</th>
<th>Product Quantity</th>
<th>Product Barcode</th>
</tr>
</thead>
<tbody id="plist">
<tr>
<td> product name 1</td>
<td>product price 1</td>
<td>product quantity 1</td>
<td>product bardcode 1</td>
</tr>
</tbody>
</table>
The JS Code used here is:
<script>
const formel = document.querySelector('#input');
const tableel=document.querySelector('#plist');
function addRow(e){
e.preventDefault;
const pname = document.getElementById('productname').value;
const pprice = document.getElementById('productprice').value;
const pquan = document.getElementById('productquantity').value;
const pcode = document.getElementById('productcode').value;
tableel.innerHTML = `
<tr>
<td>${pname}</td>
<td>${pprice}</td>
<td>${pquan}</td>
<td>${pcode}</td>
</tr>
`;
}
formel.addEventListener("submit", addRow)
</script>
The item gets added for a few seconds/millions, immediately gets deleted. I tried checking the console, it shows no error.
I am new to javascript, honestly, I got js code by watching various YouTube videos, but I can't understand why will the table row get immediately deleted after being added.
If anybody helps it will really be helpful, thank you in adavance.
CodePudding user response:
Since preventDefault is a method, you need to change e.preventDefault
to e.preventDefault();
.
Ref: https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault
CodePudding user response:
Since you haven't call e.preventDefault, click on the Add Products button makes a request and sends form's data to server, then it shows this request's response (which is nothing) as a result after some miliseconds you can see just an empty page. To solve the problem you need to change e.preventDefault to e.preventDefault() and this change prevents submiting the form.