Read table contents

by dshilkret

HTML

<table class="mytable">
  <tr>
    <td>01</td>
    <td>price01</td>
    <td>location01</td>
  </tr>
  
  <tr>
    <td>02</td>
    <td>price02</td>
    <td>location02</td>
  </tr> 
</table>

<button id="click">Click Me</button>

<div id="01" class="place">This is 01</div>
<div id="02" class="place">This is 02</div>

CSS

td { border: 1px solid green; padding: 5px; }
button { margin: 5px 0px; }
.place { border: 1px solid blue; padding: 10px; margin: 5px 0px; }

JavaScript

$('#click').click(function() {
    //loop through each table row
    $(".mytable").find("tr").each(function () {
        //get the ID from the first TD
        var ID = $(this).children(':first').text();
        
        //create an array to hold the info from each TD within a TR
        var rowInfo = new Array();
        
        //loop through each TD in the row and add the text to the array
        $(this).children('td').each(function() {
            rowInfo.push($(this).text());
        })
        
        //create a string from the array, separated by a PIPE (|) character
        newString = rowInfo.join(" | ");
        
        //pop the new string into the relavant DIV
        $("#" + ID).html(newString);
    });
});