skip to Main Content

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:

  1. Validate user input (e.g., check if item name is not empty and price is a positive number).
  2. Update the table rows dynamically when the user changes the input fields.
  3. 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


  1. Below is complete solution of your problem

    $(document).ready(function () {
      $("#add-item").click(function() {
        var itemName = $("#item-name").val().trim();
        var itemPrice = $("#item-price").val();
    
        if (!validateInputs(itemName, itemPrice)) {
          return;
        }
    
        if (isDuplicate(itemName)) {
          alert("Item already exists!");
          return;
        }
        var newRow = $("<tr>");
        newRow.append($("<td>").text(itemName));
        newRow.append($("<td>").text(itemPrice));
    
        $("#item-table tbody").append(newRow);
        $("#item-name").val("");
        $("#item-price").val("");
      });
      function validateInputs(itemName, itemPrice) {
        var isValid = true;
        $(".error").removeClass("error");
        if (!itemName) {
          $("#item-name").addClass("error");
          isValid = false;
        }
    
        if (!itemPrice || itemPrice <= 0) {
          $("#item-price").addClass("error");
          isValid = false;
        }
    
        return isValid;
      }
      function isDuplicate(itemName) {
        let exists = false;
        $("#item-table tbody tr").each(function () {
          if ($(this).find("td").first().text() === itemName) {
            exists = true;
          }
        });
        return exists;
      }
      $("#item-name, #item-price").on("input", function () {
        var itemName = $("#item-name").val().trim();
        var itemPrice = $("#item-price").val();
        if (itemName && itemPrice > 0) {
          $("#item-table tbody tr").each(function () {
            if ($(this).find("td").first().text() === itemName) {
              $(this).find("td").last().text(itemPrice);
            }
          });
        }
      });
    });
    input.error {
      border: 2px solid red;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <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>
    
    <table id="item-table">
      <thead>
        <tr>
          <th>Item</th>
          <th>Price</th>
        </tr>
      </thead>
      <tbody></tbody>
    </table>
    Login or Signup to reply.
  2. 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

    <script>
        $(document).ready(function() {
          // Add item to table
          $('#add-item').click(function() {
            // Get user input
            var itemName = $('#item-name').val().trim();
            var itemPrice = parseFloat($('#item-price').val());
    
            // Input validation
            if (itemName === '') {
              alert('Item name cannot be empty.');
              return;
            }
            if (isNaN(itemPrice) || itemPrice <= 0) {
              alert('Please enter a valid positive price.');
              return;
            }
    
            // Check if item name already exists in the table
            var exists = false;
            $('#item-table tbody tr').each(function() {
              var currentName = $(this).find('td:first').text();
              if (currentName.toLowerCase() === itemName.toLowerCase()) {
                exists = true;
                return false; // break the loop
              }
            });
    
            if (exists) {
              alert('Item already exists.');
              return;
            }
    
            // Create new table row
            var newRow = $('<tr>');
            newRow.append($('<td>').text(itemName));
            newRow.append($('<td>').text(itemPrice.toFixed(2)));
            
            // Add edit and delete buttons
            var actionsCell = $('<td>');
            var editBtn = $('<button>').text('Edit');
            var deleteBtn = $('<button>').text('Delete');
    
            // Attach event handlers for edit and delete
            editBtn.click(function() {
              var row = $(this).closest('tr');
              var currentItem = row.find('td:eq(0)').text();
              var currentPrice = row.find('td:eq(1)').text();
              $('#item-name').val(currentItem);
              $('#item-price').val(currentPrice);
              row.remove();
            });
    
            deleteBtn.click(function() {
              $(this).closest('tr').remove();
            });
    
            actionsCell.append(editBtn).append(' ').append(deleteBtn);
            newRow.append(actionsCell);
    
            // Add the new row to the table
            $('#item-table tbody').append(newRow);
    
            // Clear input fields
            $('#item-name').val('');
            $('#item-price').val('');
          });
        });
      </script>
    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Dynamic Table with Validation</title>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    </head>
    <body>
      <table id="item-table" border="1">
        <thead>
          <tr>
            <th>Item</th>
            <th>Price</th>
            <th>Actions</th>
          </tr>
        </thead>
        <tbody>
          <!-- rows will be generated dynamically -->
        </tbody>
      </table>
    
      <br>
    
      <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>
    </body>
    </html>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search