Jackson Sentzke Jackson Sentzke - 1 year ago 60
Ajax Question

Change table contents depending on link clicked

I have 2 HTML tables. I'm trying to change the contents of the second table depending on what link is pressed in the first table.

Below is the code that populates the first table:

$.each(tableResults, function () {
$('#table1 tbody:last-child').append('<td>' + this + '</td>');

And below is the code that populates the second table:

$(document).ready(function () {
var tableName = 'databaseTable1';
url: 'http://localhost/api/Dynamic?table=' + tableName,
dataType: 'Json',
success: function (tableResults) {
$.each(tableResults, function (index, value) {
if ($('#table2 th:last-child').length === 0) {
$('#table2 thead').append('<th>' + value + '</th>');
} else {
$('#table2 th:last-child').after('<th>' + value + '</th>');

As you can see the tables are populated dynamically. I need to know how to turn each value in the first table into a link that'll change the variable
into the value selected.

The page should then refresh and display the data from the selected table. If it helps my program has an
back end.

Also on a side note, does anyone know how I could set
default value to the first value in

Any help would be appreciated.

Answer Source

You can store the tableNames in the attribute of the trigger element (such as a). Then, when the user clicks on this trigger, get the tableName from the attribute using .attr().

I don't know your response so in my example there is a dummy one.

(Click on any line and see the tableName in the log.

var tableResults = [
    name: 'dynamicTable1'
    name: 'dynamicTable2'

$.each(tableResults, function () {
  $('#table1 tbody:last-child').append('<tr><td><a data-table="' + this.name + '">' + this.name + '</a></td></tr>'); 

$(document).on('click','[data-table]', function(){
  var link = $(this),
      tableName = link.attr('data-table');


  // do your ajax call with tableName
  // $.ajax({ ....
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<table id="table1">
<hr />
<table id="table2">



  1. The page should then refresh and display the data

    By refresh you mean ajax "refresh"? Otherwise why you need an ajax?

  2. You can't put td in tbody so you need to add a row (tr) too.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download