var $tbody; $(document).ready(function () { //Simulate Ajax call here to get customer data var custs = getCustomerData(); $tbody = $('#tableBody'); for (var i = 0; i < custs.length; i++) { var $tr = $('<tr><td>' + custs[i].Name + '</td><td>' + custs[i].City + '</td></tr>'); //Associate customer data with the row $tr.data('custData', custs[i]); //NOTE: Not generally efficient to manipulate the DOM in a loop //if you have a large number of rows $tbody.append($tr); } //Handle row click $tbody.on('click', 'tr', function () { //Get to row data var custData = $(this).data('custData'); //Show State alert('Name: ' + custData.Name + '\r\nState: ' + custData.State + '\r\nCity: ' + custData.City); }); }); function getCustomerData() { return [ { ID: 1, Name: 'John', City: 'Scottsdale', State: 'AZ' }, { ID: 2, Name: 'Jane', City: 'Chandler', State: 'AZ' }, { ID: 3, Name: 'Michelle', City: 'San Diego', State: 'CA' }, { ID: 4, Name: 'James', City: 'Portland', State: 'OR' }, { ID: 5, Name: 'Tom', City: 'Dallas', State: 'TX' }, ]; }
Click on a row to access customer data using .data() <br /><br /> <table style="width:400px;"> <thead style="background-color:#efefef"> <tr> <td>Name</td> <td>City</td> </tr> </thead> <tbody id="tableBody"></tbody> </table>
tr { cursor:pointer }