Search code examples
javascriptphpjqueryhtml-table

Adding data dynamically to HTML Table in PHP


I want to add data's from input fields to the HTML Table dynamically when clicking the Add button as shown in the sample image. How can I accomplish this? Can I do it with PHP? As I'm a beginner I can't find the exactly matched results from here, but I found a related thread, Creating a dynamic table using php based on users input data, but I think this process is done by 2 pages (1 page for inputs and another for showing that input data's in table) as per the code... Any help will appreciated.


Solution

  • Assuming you're using jquery (given your tag), something like the following will work:

    $("button").click(function() {
      var newRow = "<tr>";
    
      $("form input").each(function() {
        newRow += "<td>"+$(this).val()+"</td>";
      });
    
      newRow += "</tr>";
    
      $("table").append(newRow);
    });
    

    There are better ways to do this, but this is probably a very simple place to start if you're just beginning to learn. The functions you should be interested in here are: .click, .each, .val, and .append. I'd recommend you check out the jquery docs - they will give you good examples to expand your knowledge.