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.
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, 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!
$(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);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<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>
2
Answers
Below is complete solution of your problem
An Edit button is added next to each row. Clicking the Edit button will populate the input fields with the existing values and remove the row so you can update it. A Delete button is added, which allow to remove the row from the table. Also added comments in code for better understanding