I’m trying to create a dynamic HTML table that updates its rows based on user input. The table should display a list of items with their corresponding prices.
HTML:
<table id="item-table">
<thead>
<tr>
<th>Item</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<!-- rows will be generated dynamically -->
</tbody>
</table>
<input type="text" id="item-name" placeholder="Enter item name">
<input type="number" id="item-price" placeholder="Enter item price">
<button id="add-item">Add Item</button>
JavaScript (jQuery):
$(document).ready(function() {
$('#add-item').click(function() {
// Get user input
var itemName = $('#item-name').val();
var itemPrice = $('#item-price').val();
// Create new table row
var newRow = $('<tr>');
newRow.append($('<td>').text(itemName));
newRow.append($('<td>').text(itemPrice));
// Add row to table body
$('#item-table tbody').append(newRow);
});
});
**Problem:
**
When the user clicks the “Add Item” button, the new row is added, but I want to:
- Validate user input (e.g., check if item name is not empty and price is a positive number).
- Update the table rows dynamically when the user changes the input fields.
- Remove duplicate item names.
~~- Using change
event on input fields, but it doesn’t update the table rows.~~~~
- Using
blur
event on input fields, but it doesn’t validate input
Any guidance or code snippets would be greatly appreciated!
Edit: I’ve updated the code to use change
event, but still facing issues.
Would you like me to modify or add anything to this question?