Tyler Tyler - 3 months ago 11
HTML Question

Updating html table with input

I am a learning js, html, css, and general web development for the first time and I wanted to create a simple (or so I thought) table that I could use personally for keeping track of items that I currently have.

Essentially what I want to do is make a dynamically-sized table that can take and save input.

I was thinking of a way to make some javascript function in order to add tags into my tables from the input given. I have seen a personal website where the developer had input boxes with a submit button, causes the data to be added in to a table in another html file's table.

For instance, if I have:

<table id="inventory">
<thead>
<tr>
<th>Item Name</th>
<th>Item Number</th>
<th>Item Color</th>
</tr>
</thead>
</table>


Would it be possible for me to say add

<tr class = "boxType">
<th>BoxV1</th>
<th>#1111</th>
<th>Blue</th>
</tr>


The above block into the table using javascript and inputs?

I tried making an addRows method after snooping around the web, and that created a temporary version of the table that would be empty when refreshed (meaning it wasn't put into the code, but rather added on for that session), I want to permanently stick it into the table if possible.

edit: Some thoughts I have:

I feel like something can be done if i make a <tbody id ="list"> and use some form of innerHTML to add the <tr> block in?

maybe using some php form in order to update the html table block?

Thank you!

Answer

Use innerHtml or jQuery html() function and localstorage to keep track of update dom content. Also remember to reload old data on page load. See my full example:

http://jsbin.com/voroku/edit?html,output

HTML INPUT:

<input type="text" id="one">
<input type="text" id="two">
<input type="text" id="three">
<button onclick="addRow()">ADD</button>

JS FUNCTION:

$( document ).ready(function(){
  $('#screen').html(localStorage.getItem("data"));

});
 function addRow(){
      var str = '<tr class = "boxType">\
                 <td>'+$('#one').val()+'</td>\
                 <td>'+$('#two').val()+'</td>\
                 <td>'+$('#three').val()+'</td>\
                 </tr>';
      $('#screen').append(str);

      localStorage.setItem("data", $('#screen').html());
    }
Comments