Create A Common Function To Use Same For Other Data
I am making a list of item and want to calculate its value as quantity change, but how to make the function common so that I can use it for all row? Can you suggest some best and e
Solution 1:
Rather than using inline handlers (which are generally considered to be pretty bad practice), you can use event delegation on the table
itself, and you can keep your code DRY-er if you have a single function that handles number changes, rather than two. If the target (the clicked element) matches a +
button, call with a parameter of 1
, and if the target matches a -
button, call with a parameter of -1
. Also pass the target - from it, you can identify the associated quantity
, price
, and total
elements in the same <tr>
by accessing the parentElement
s of the button.
With this implementation, all the data is stored in the HTML itself - there are no persistent variables, and there's no need for any IDs anymore.
document.querySelector('table').addEventListener('click', ({ target }) => {
if (target.matches('button:nth-child(1)')) changeNum(target, 1);
else if (target.matches('button:nth-child(2)')) changeNum(target, -1);
});
function changeNum(button, changeBy) {
const [, quantityElm, priceElm, totalElm] = button.parentElement.parentElement.children;
const quantity = Number(quantityElm.textContent) + changeBy;
quantityElm.textContent = quantity;
const price = Number(priceElm.textContent);
const total = quantity * price;
totalElm.textContent = total;
}
<table>
<thead>
<tr>
<th>
Name
</th>
<th>Quantitiy</th>
<th>Price</th>
<th>Total</th>
</tr>
</thead>
<tbody>
<tr>
<td>item</td>
<td>0</td>
<td>25</td>
<td>0</td>
<td>
<button>+</button>
<button>-</button>
</td>
</tr>
<tr>
<td>item</td>
<td>0</td>
<td>5</td>
<td>0</td>
<td>
<button>+</button>
<button>-</button>
</td>
</tr>
<tr>
<td>item</td>
<td>0</td>
<td>5</td>
<td>0</td>
<td> <button>+</button>
<button>-</button></td>
</tr>
</tbody>
</table>
Post a Comment for "Create A Common Function To Use Same For Other Data"