Jackson Sentzke Jackson Sentzke - 2 months ago 6
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';
$.ajax({
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
tableName
into the value selected.

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

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

Any help would be appreciated.

Answer

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');

  console.log(tableName);

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

http://jsbin.com/jicihohama/edit?html,js,console,output

Notes:

  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.