TableView with WebViewer, JavaScript and CSS. Helped by chat.openai GPT. Perplexity

In this Community you can find several ways to present a table, for example with the extensions:

TableView Extension Versions 3 and 4 by @Ken [As of App Inventor version nb191 (February 2023), this extension produces errors.]

TableViewer - fully style customized to show table by @Kevinkun [We must feed the blocks of this extension with CSS code.]

Here we are going to display tables using WebViewer, JavaScript and CSS. We'll use GPT to show us codes, which we can customize.

Let's apply to GPT-3.5:
We have a string to build a table with 4 columns, the number of rows is a variable, show me a web page showing a table built with CSS, the rows should alternate between light green and light red. Information within cells should appear centered. When we click on a cell, an alert should appear with the content of that cell. Use JavaScript. The string must be passed as a variable, for example 1,2,3,4\n5,6,7,8\n...

1 Like

1.- We get the following code:

tablacss.htm
<!DOCTYPE html>
<html>
<head>
  <title>Table with CSS</title>
  <style>
    table {
      border-collapse: collapse;
      width: 100%;
      max-width: 800px;
      margin: 0 auto;
    }
    th, td {
      padding: 8px;
      text-align: center;
      border: 1px solid #000;
    }
    th {
      background-color: #f2f2f2;
    }
    tr:nth-child(even) {
      background-color: #d1f0d1;
    }
    tr:nth-child(odd) {
      background-color: #ffdede;
    }
  </style>
</head>
<body>
   Click on a cell.<br><br>
  <div id="table-container"></div>

  <script>
    var string = "1,2,3,4\n5,6,7,8\n9,10,11,12\n13,14,15,16";
    var rows = string.split("\n");
    var table = document.createElement("table");

    var headerRow = document.createElement("tr");
    var headerCell1 = document.createElement("th");
    var headerCell2 = document.createElement("th");
    var headerCell3 = document.createElement("th");
    var headerCell4 = document.createElement("th");
    headerCell1.appendChild(document.createTextNode("Column 1"));
    headerCell2.appendChild(document.createTextNode("Column 2"));
    headerCell3.appendChild(document.createTextNode("Column 3"));
    headerCell4.appendChild(document.createTextNode("Column 4"));
    headerRow.appendChild(headerCell1);
    headerRow.appendChild(headerCell2);
    headerRow.appendChild(headerCell3);
    headerRow.appendChild(headerCell4);
    table.appendChild(headerRow);

    for (var i = 0; i < rows.length; i++) {
      var cols = rows[i].split(",");
      var row = document.createElement("tr");
      if (i % 2 == 0) {
        row.style.backgroundColor = "#d1f0d1";
      } else {
        row.style.backgroundColor = "#ffdede";
      }
      for (var j = 0; j < cols.length; j++) {
        var cell = document.createElement("td");
        cell.appendChild(document.createTextNode(cols[j]));
        cell.addEventListener("click", function() {
          alert(this.innerHTML);
        });
        row.appendChild(cell);
      }
      table.appendChild(row);
    }

    document.getElementById("table-container").appendChild(table);
  </script>
</body>
</html>

Here we can see the result, when we click on a cell, we get an alert with its content.

http://kio4.com/appinventor/javascript/tablacss.htm

  • We adapt it to App Inventor by changing these lines:
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0">
(...)
 // var string = "1,2,3,4\n5,6,7,8\n9,10,11,12\n13,14,15,16";
	var string =  window.AppInventor.getWebViewString(); // INPUT
(...)
      // alert(rowContent);
	    window.AppInventor.setWebViewString(rowContent); // OUTPUT

- App Inventor.

p170F_JavaScriptTablaCSS.aia (5.4 KB)

2.- Show a row.

Now we want that instead of showing the content of a cell, it shows the content of the entire row.

We ask GPT:
In the above code when we click on a cell we get an alert with its content, I want that when we click on a cell we get an alert with the content of its entire row.

tablacss_row.htm
<!DOCTYPE html>
<html>
<head>
  <title>Table with CSS</title>
  <style>
    table {
      border-collapse: collapse;
      width: 100%;
      max-width: 800px;
      margin: 0 auto;
    }
    th, td {
      padding: 8px;
      text-align: center;
      border: 1px solid #000;
    }
    th {
      background-color: #f2f2f2;
    }
    tr:nth-child(even) {
      background-color: #d1f0d1;
    }
    tr:nth-child(odd) {
      background-color: #ffdede;
    }
  </style>
</head>
<body>
   Click on a cell.<br><br>
  <div id="table-container"></div>

  <script>
    var string = "1,2,3,4\n5,6,7,8\n9,10,11,12\n13,14,15,16";
    var rows = string.split("\n");
    var table = document.createElement("table");

    var headerRow = document.createElement("tr");
    var headerCell1 = document.createElement("th");
    var headerCell2 = document.createElement("th");
    var headerCell3 = document.createElement("th");
    var headerCell4 = document.createElement("th");
    headerCell1.appendChild(document.createTextNode("Column 1"));
    headerCell2.appendChild(document.createTextNode("Column 2"));
    headerCell3.appendChild(document.createTextNode("Column 3"));
    headerCell4.appendChild(document.createTextNode("Column 4"));
    headerRow.appendChild(headerCell1);
    headerRow.appendChild(headerCell2);
    headerRow.appendChild(headerCell3);
    headerRow.appendChild(headerCell4);
    table.appendChild(headerRow);

    for (var i = 0; i < rows.length; i++) {
      var cols = rows[i].split(",");
      var row = document.createElement("tr");
      if (i % 2 == 0) {
        row.style.backgroundColor = "#d1f0d1";
      } else {
        row.style.backgroundColor = "#ffdede";
      }
for (var j = 0; j < cols.length; j++) {
        var cell = document.createElement("td");
        cell.appendChild(document.createTextNode(cols[j]));
        row.appendChild(cell);
      }
      row.addEventListener("click", function() {
        var rowContent = "";
        for (var k = 0; k < this.cells.length; k++) {
          rowContent += this.cells[k].innerHTML + "|";
        }
        alert(rowContent);
      });
      table.appendChild(row);
    }
	
    document.getElementById("table-container").appendChild(table);
  </script>
</body>
</html>

http://kio4.com/appinventor/javascript/tablacss_row.htm

3.- Sort the table when we click the header of a column.

We ask GPT:
Also, if I click on the header of a column, all the columns will be sorted alphanumerically according to the column clicked.

tablacss_sort.htm
<!DOCTYPE html>
<html>
<head>
  <title>Tabla con CSS y ordenamiento</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0">
  <style>
    table {
      border-collapse: collapse;
      width: 100%;
      max-width: 800px;
      margin: 0 auto;
    }
    th, td {
      padding: 8px;
      text-align: center;
      border: 1px solid #000;
      cursor: pointer;
    }
    th {
      background-color: #f2f2f2;
    }
    tr:nth-child(even) {
      background-color: #d1f0d1;
    }
    tr:nth-child(odd) {
      background-color: #ffdede;
    }
  </style>
</head>
<body>
  Click on a header.<br><br>
  <div id="table-container"></div>

  <script>
    var string = "Fernando,33,Granada,4\nAntonio,66,Sevilla,3\nLuis,55,Cadiz,2\nCarlos,44,Cordoba,1";
    var rows = string.split("\n");
    var table = document.createElement("table");

    var headerRow = document.createElement("tr");
    var headerCell1 = document.createElement("th");
    var headerCell2 = document.createElement("th");
    var headerCell3 = document.createElement("th");
    var headerCell4 = document.createElement("th");
    headerCell1.appendChild(document.createTextNode("Columna 1"));
    headerCell2.appendChild(document.createTextNode("Columna 2"));
    headerCell3.appendChild(document.createTextNode("Columna 3"));
    headerCell4.appendChild(document.createTextNode("Columna 4"));
    headerCell1.addEventListener("click", function() { sortTable(0); });
    headerCell2.addEventListener("click", function() { sortTable(1); });
    headerCell3.addEventListener("click", function() { sortTable(2); });
    headerCell4.addEventListener("click", function() { sortTable(3); });
    headerRow.appendChild(headerCell1);
    headerRow.appendChild(headerCell2);
    headerRow.appendChild(headerCell3);
    headerRow.appendChild(headerCell4);
    table.appendChild(headerRow);

    var data = [];
    var firstRowColor = "#d1f0d1"; // color of the first row after the header
    for (var i = 0; i < rows.length; i++) {
      var cols = rows[i].split(",");
      data.push(cols);
      var row = document.createElement("tr");
      if (i === 0) {
        row.style.backgroundColor = firstRowColor;
      } else {
        row.style.backgroundColor = i % 2 === 0 ? firstRowColor : "#ffdede";
      }
      for (var j = 0; j < cols.length; j++) {
        var cell = document.createElement("td");
        cell.appendChild(document.createTextNode(cols[j]));
        row.appendChild(cell);
      }
      row.addEventListener("click", function() {
        var rowContent = "";
        for (var k = 0; k < this.cells.length; k++) {
          rowContent += this.cells[k].innerHTML + "|";
        }
         alert(rowContent);
      });
      table.appendChild(row);
    }

    document.getElementById("table-container").appendChild(table);

function sortTable(col) {
  var rows = table.rows;
  var switching = true;
  var shouldSwitch = false;
  var i = 1;
  var even = true;
  while (switching) {
    switching = false;
    for (var j = 1; j < (rows.length - 1); j++) {
      shouldSwitch = false;
      var x = rows[j].getElementsByTagName("td")[col];
      var y = rows[j + 1].getElementsByTagName("td")[col];
      if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase()) {
        shouldSwitch = true;
        break;
      }
    }
    if (shouldSwitch) {
      rows[j].parentNode.insertBefore(rows[j + 1], rows[j]);
      switching = true;
    }
  }
  // Alternate color background row.
  for (var k = 1; k < rows.length; k++) {
    if (k % 2 === 0) {
      rows[k].style.backgroundColor = "#d1f0d1";
    } else {
      rows[k].style.backgroundColor = "#ffdede";
    }
  }
}

  </script>
</body>
</html>

http://kio4.com/appinventor/javascript/tablacss_sort.htm

4.- With images.

tablacss_sort_images.htm
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
  <title>Tabla con CSS y ordenamiento</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0">
  <style>
    table {
      border-collapse: collapse;
      width: 100%;
      max-width: 800px;
      margin: 0 auto;
    }
    th, td {
      padding: 8px;
      text-align: center;
      border: 1px solid #000;
      cursor: pointer;
    }
    th {
      background-color: #f2f2f2;
    }
    tr:nth-child(even) {
      background-color: #d1f0d1;
    }
    tr:nth-child(odd) {
      background-color: #ffdede;
    }
  </style>
</head>
<body>
  Click on a header.<br><br>
  <div id="table-container"></div>
  <script>
    // var string = "<img src='perro_50t.png'>,Perro,33,04\n<img src='gato_50t.png'>,Gato,66,03\n<img src='pajaro_50t.png'>,Pájaro,55,02\n<img src='cerdo_50t.png'>,Cerdo,44,01\n<img src='raton_50t.png'>,Ratón,77,05\n<img src='elefante_50t.png'>,Elefante,22,06\n<img src='vaca_50t.png'>,Vaca,33,07\n<img src='jirafa_50t.png'>,Jirafa,44,08\n<img src='buho_50t.png'>,Buho,55,09\n<img src='mono_50t.png'>,Mono,66,10\n<img src='cebra_50t.png'>,Cebra,77,11";
	var string =  window.AppInventor.getWebViewString(); // INPUT
    var rows = string.split("\n");
    var table = document.createElement("table");

    var headerRow = document.createElement("tr");
    var headerCell1 = document.createElement("th");
    var headerCell2 = document.createElement("th");
    var headerCell3 = document.createElement("th");
    var headerCell4 = document.createElement("th");
    headerCell1.appendChild(document.createTextNode("Columna 1"));
    headerCell2.appendChild(document.createTextNode("Columna 2"));
    headerCell3.appendChild(document.createTextNode("Columna 3"));
    headerCell4.appendChild(document.createTextNode("Columna 4"));
    headerCell1.addEventListener("click", function() { sortTable(0); });
    headerCell2.addEventListener("click", function() { sortTable(1); });
    headerCell3.addEventListener("click", function() { sortTable(2); });
    headerCell4.addEventListener("click", function() { sortTable(3); });
    headerRow.appendChild(headerCell1);
    headerRow.appendChild(headerCell2);
    headerRow.appendChild(headerCell3);
    headerRow.appendChild(headerCell4);
    table.appendChild(headerRow);

    var data = [];
    var firstRowColor = "#d1f0d1"; // color of the first row after the header
    for (var i = 0; i < rows.length; i++) {
      var cols = rows[i].split(",");
      data.push(cols);
      var row = document.createElement("tr");
      if (i === 0) {
        row.style.backgroundColor = firstRowColor;
      } else {
        row.style.backgroundColor = i % 2 === 0 ? firstRowColor : "#ffdede";
      }
      for (var j = 0; j < cols.length; j++) {
        var cell = document.createElement("td");
	
	 if (cols[j].startsWith("<img")) {
		cell.innerHTML = cols[0];
      } else {
		cell.appendChild(document.createTextNode(cols[j]));
      }
		row.appendChild(cell);
      }
      row.addEventListener("click", function() {
        var rowContent = "";
        for (var k = 0; k < this.cells.length; k++) {
          rowContent += this.cells[k].innerHTML + "|";
        }
        // alert(rowContent);
		 window.AppInventor.setWebViewString(rowContent); // OUTPUT
      });
      table.appendChild(row);
    }

    document.getElementById("table-container").appendChild(table);

function sortTable(col) {
  var rows = table.rows;
  var switching = true;
  var shouldSwitch = false;
  var i = 1;
  var even = true;
  while (switching) {
    switching = false;
    for (var j = 1; j < (rows.length - 1); j++) {
      shouldSwitch = false;
      var x = rows[j].getElementsByTagName("td")[col];
      var y = rows[j + 1].getElementsByTagName("td")[col];
      if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase()) {
        shouldSwitch = true;
        break;
      }
    }
    if (shouldSwitch) {
      rows[j].parentNode.insertBefore(rows[j + 1], rows[j]);
      switching = true;
    }
  }
  // Alternate color background row.
  for (var k = 1; k < rows.length; k++) {
    if (k % 2 === 0) {
      rows[k].style.backgroundColor = "#d1f0d1";
    } else {
      rows[k].style.backgroundColor = "#ffdede";
    }
  }
}

  </script>
</body>
</html>

http://kio4.com/appinventor/javascript/tablacss_sort_image.htm

p170F_JavaScriptTablaCSS_v2.aia (71.7 KB)

1 Like
  • GPT will give you codes that can be different each time you click on "Regenerate response", you must adapt it to your needs.

  • With this new tool we can easily learn to create and adjust codes.

  • There are two negative features that I have seen in chat.open GPT:

a) To register, we are asked to write our telephone number to confirm the registration.
b) Sometimes it shows the incomplete code and we must tell it to show the missing code.

Let's try another AI: perplexity

https://www.perplexity.ai/

  • To register, it only asks us for an email account (gmail), it does not ask for a telephone number.
  • It usually shows the complete code, although sometimes in the middle of the code it appears indicating that the code continues.

5.- PERPLEXITY. Create a table that can be sorted by columns.

We ask for it:

I have the string = "Fernando,33,Granada,04\nAntonio,66,Sevilla,03\nLuis,55,Cádiz,02\nCarlos,44,Córdoba,01\nRicardo,77,Huelva,05", I want to display it in a table built with HTML, JavaScript and CSS. By clicking on the header of each column, SortUp and SortDown must be ordered. Row colors should alternate between light red and light green, even when sorted. Cells must have a black border. Show the code.

I ask the question in Spanish, as I have shown in the previous image.

I get:

tablacss_orden.htm
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Tabla ordenable</title>
  <style>
    table {
      border-collapse: collapse;
      width: 100%;
    }
    th, td {
      text-align: left;
      padding: 8px;
      cursor: pointer;
      border: 1px solid black;
    }
    th {
      background-color: #4CAF50;
      color: white;
    }
    tr:nth-child(even) {
      background-color: #c8f7c5;
    }
    tr:nth-child(odd) {
      background-color: #f7c5c5;
    }
    .headerSortUp:after,
    .headerSortDown:after {
      content: ' ';
      position: relative;
      left: 5px;
    }
    .headerSortUp:after {
      border-bottom: 8px solid #fff;
      border-left: 5px solid transparent;
      border-right: 5px solid transparent;
    }
    .headerSortDown:after {
      border-top: 8px solid #fff;
      border-left: 5px solid transparent;
      border-right: 5px solid transparent;
    }
  </style>
  <script>
    function sortTable(n) {
      var table, rows, switching, i, x, y, shouldSwitch, dir, switchcount = 0;
      table = document.getElementById("myTable");
      switching = true;
      dir = "asc";
      while (switching) {
        switching = false;
        rows = table.rows;
        for (i = 1; i < (rows.length - 1); i++) {
          shouldSwitch = false;
          x = rows[i].getElementsByTagName("TD")[n];
          y = rows[i + 1].getElementsByTagName("TD")[n];
          if (dir == "asc") {
            if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase()) {
              shouldSwitch = true;
              break;
            }
          } else if (dir == "desc") {
            if (x.innerHTML.toLowerCase() < y.innerHTML.toLowerCase()) {
              shouldSwitch = true;
              break;
            }
          }
        }
        if (shouldSwitch) {
          rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
          switching = true;
          switchcount ++;
        } else {
          if (switchcount == 0 && dir == "asc") {
            dir = "desc";
            switching = true;
          }
        }
      }
      // Add CSS classes to indicate sorting direction
      var th = table.getElementsByTagName("TH");
      for (i = 0; i < th.length; i++) {
        th[i].classList.remove("headerSortUp");
        th[i].classList.remove("headerSortDown");
      }
      if (dir == "asc") {
        th[n].classList.add("headerSortUp");
      } else if (dir == "desc") {
        th[n].classList.add("headerSortDown");
      }
      // Alternate row colors
      var rows = table.getElementsByTagName("TR");
      for (i = 0; i < rows.length; i++) {
        var color = i % 2 == 0 ? "#f7c5c5" : "#c8f7c5";
        rows[i].style.backgroundColor = color;
      }
    }

    function createTable(data) {
      var rows = data.split("\n");
      var table = "<table id='myTable'>";
      table += "<thead><tr>";
      table += "<th onclick='sortTable(0)'>Nombre</th>";
      table += "<th onclick='sortTable(1)'>Edad</th>";
      table += "<th onclick='sortTable(2)'>Ciudad</th>";
      table += "<th onclick='sortTable(3)'>Código postal</th>";
      table += "</tr></thead>";
      table += "<tbody>";
      for (var i = 0; i < rows.length; i++) {
        var cells = rows[i].split(",");
        var color = i % 2 == 0 ? "#f7c5c5"  : "#c8f7c5";
        table += "<tr style='background-color: " + color + "'>";
        for (var j = 0; j < cells.length; j++) {
          table += "<td>" + cells[j] + "</td>";
        }
        table += "</tr>";
      }
      table += "</tbody></table>";
      return table;
    }

    window.onload = function() {
      var data = "Fernando,33,Granada,04\nAntonio,66,Sevilla,03\nLuis,55,Cádiz,02\nCarlos,44,Córdoba,01\nRicardo,77,Huelva,05";
      var table = createTable(data);
      document.getElementById("tableContainer").innerHTML = table;
    };
  </script>
</head>
<body>
  <div id="tableContainer"></div>
</body>
</html>

http://kio4.com/appinventor/javascript/tablacss_orden.htm

  • I adapt it to App Inventor by changing:
window.onload = function() {
      // var data = "Fernando,33,Granada,04\nAntonio,66,Sevilla,03\nLuis,55,Cádiz,02\nCarlos,44,Córdoba,01\nRicardo,77,Huelva,05";
	  var data =  window.AppInventor.getWebViewString(); // INPUT

p170F_JavaScriptTablaCSS_v3.aia (7.0 KB)

1 Like

6.- Perplexity. Graphic.

If instead of showing the data in a table we want it in a graph, we can also show it in a web page.

Perplexity:

I have the following values ​​in two Strings Y="10,40,03,20,60,40,30,60,29,70" X="1,2,3,4,5,6,7,8,9 ,10". I want to display those values ​​graphically on a page with HTML, JavaScript, and Css. Show me the full code.

grafica.htm
<!DOCTYPE html>
<html>
<head>
	<title>Gráfico de Y y X</title>
	<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
	<style>
		canvas {
			max-width: 800px;
			max-height: 600px;
			margin: 0 auto;
			display: block;
		}
	</style>
</head>
<body>
	<canvas id="myChart"></canvas>
	<script>
		// Obtener los valores de Y y X
	   var yValues = "10,40,03,20,60,40,30,60,29,70";
	   var xValues = "1,2,3,4,5,6,7,8,9,10";	
		var yArray = yValues.split(",");
		var xArray = xValues.split(",");

		// Crear un objeto de gráfico
		var ctx = document.getElementById('myChart').getContext('2d');
		var myChart = new Chart(ctx, {
			type: 'line',
			data: {
				labels: xArray,
				datasets: [{
					label: 'Valores de Y',
					data: yArray,
					backgroundColor: 'rgba(255, 99, 132, 0.2)',
					borderColor: 'rgba(255, 99, 132, 1)',
					borderWidth: 1
				}]
			},
			options: {
				scales: {
					yAxes: [{
						ticks: {
							beginAtZero: true
						}
					}]
				}
			}
		});
	</script>
</body>
</html>

http://kio4.com/appinventor/javascript/grafica.htm

  • We adapt the code to App Inventor
	  // Obtener los valores de Y y X
	  // var yValues = "10,40,03,20,60,40,30,60,29,70";
	  // var xValues = "1,2,3,4,5,6,7,8,9,10";
		var string =  window.AppInventor.getWebViewString().split("|"); // INPUT
		var yValues = string[0];
		var xValues = string[1];
(...)

p170F_JavaScriptTablaCSS_v4.aia (7.9 KB)

javascriptTabla8

1 Like

7.- Sort table click header. SortUp. SortDown. Get row when clicked cell.

http://kio4.com/appinventor/javascript/tablacss_orden_clickrow.htm

tablacss_orden_clickrow.htm
<!DOCTYPE html>
<html>
<head>
   <meta charset="UTF-8">
  <title>Tabla con CSS y ordenamiento</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0">
  <style>
    table {
      border-collapse: collapse;
      width: 100%;
      max-width: 800px;
      margin: 0 auto;
    }
    th, td {
      padding: 8px;
      text-align: center;
      border: 1px solid #000;
      cursor: pointer;
    }
    th {
      background-color: #f2f2f2;
    }
    tr:nth-child(even) {
      background-color: #d1f0d1;
    }
    tr:nth-child(odd) {
      background-color: #ffdede;
    }
  </style>
</head>
<body>
  Click on a header.<br><br>
  <div id="table-container"></div>

  <script>
 var string = "Fernando,33,Granada,04\nAntonio,66,Sevilla,03\nLuis,55,Cádiz,02\nCarlos,44,Córdoba,01\nRicardo,77,Huelva,05";
var rows = string.split("\n");
var table = document.createElement("table");
var ascending = true;

var headerRow = document.createElement("tr");
var headerCell1 = document.createElement("th");
var headerCell2 = document.createElement("th");
var headerCell3 = document.createElement("th");
var headerCell4 = document.createElement("th");
headerCell1.appendChild(document.createTextNode("Column 1"));
headerCell2.appendChild(document.createTextNode("Column 2"));
headerCell3.appendChild(document.createTextNode("Column 3"));
headerCell4.appendChild(document.createTextNode("Column 4"));

// Agregar atributos data-sort-type a cada celda del encabezado
headerCell1.setAttribute("data-sort-type", "asc");
headerCell2.setAttribute("data-sort-type", "asc");
headerCell3.setAttribute("data-sort-type", "asc");
headerCell4.setAttribute("data-sort-type", "asc");

// Agregar event listener a cada celda del encabezado
headerCell1.addEventListener("click", function() { sortTable(0); });
headerCell2.addEventListener("click", function() { sortTable(1); });
headerCell3.addEventListener("click", function() { sortTable(2); });
headerCell4.addEventListener("click", function() { sortTable(3); });

headerRow.appendChild(headerCell1);
headerRow.appendChild(headerCell2);
headerRow.appendChild(headerCell3);
headerRow.appendChild(headerCell4);
table.appendChild(headerRow);

for (var i = 0; i < rows.length; i++) {
  var cols = rows[i].split(",");
  var row = document.createElement("tr");
  if (i % 2 == 0) {
    row.style.backgroundColor = "#d1f0d1";
  } else {
    row.style.backgroundColor = "#ffdede";
  }
  for (var j = 0; j < cols.length; j++) {
    var cell = document.createElement("td");
    cell.appendChild(document.createTextNode(cols[j]));
    row.appendChild(cell);
  }
  row.addEventListener("click", function() {
    var rowContent = "";
    for (var k = 0; k < this.cells.length; k++) {
      rowContent += this.cells[k].innerHTML + "|";
    }
    alert(rowContent);
  });
  table.appendChild(row);
}

document.getElementById("table-container").appendChild(table);

function sortTable(columnIndex) {
  var rows = Array.from(table.rows).slice(1); // exclude header row
  rows.sort(function(rowA, rowB) {
    var cellA = rowA.cells[columnIndex].textContent.trim();
    var cellB = rowB.cells[columnIndex].textContent.trim();

    if (cellA < cellB) {
      return ascending ? -1 : 1;
    } else if (cellA > cellB) {
      return ascending ? 1 : -1;
    } else {
      return 0;
    }
  });

  for (var i = table.rows.length - 1; i >= 1; i--) {
    table.deleteRow(i);
  }
  
  // re-insert sorted rows
  for (var i = 0; i < rows.length; i++) {
   var row = rows[i];
  // alternar color de fondo de la fila
  if (i % 2 == 0) {
		row.style.backgroundColor = "#d1f0d1";
	  } else {
		row.style.backgroundColor = "#ffdede";
	  }

  table.appendChild(row);
  }

  // toggle sort direction for next click
  ascending = !ascending;
}
  </script>
</body>
</html>
1 Like

8.- Sort table. Google Sheet. PHP.

  • In our Google Sheet we have this sheet, we want to get a table with columns A, B, D and E.
    We are going to use a web server with PHP.

googlesheet5.php
<!DOCTYPE html>
<html>
<head>
   <meta charset="UTF-8">
  <title>Tabla con CSS y ordenamiento</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0">
  <style>
    table {
      border-collapse: collapse;
      width: 100%;
      max-width: 800px;
      margin: 0 auto;
    }
    th, td {
      padding: 8px;
      text-align: center;
      border: 1px solid #000;
      cursor: pointer;
    }
    th {
      background-color: #f2f2f2;
    }
    tr:nth-child(even) {
      background-color: #d1f0d1;
    }
    tr:nth-child(odd) {
      background-color: #ffdede;
    }
  </style>
</head>
<body>
 <?php
$url_rango1 = "https://docs.google.com/spreadsheets/d/1M9Tfz0O1a0sBwze-hobrbmdEhvivwKITijj85WKWSqM/gviz/tq?tqx=out:csv&range=A1:B21&sheet=hoja1";
$url_rango2 = "https://docs.google.com/spreadsheets/d/1M9Tfz0O1a0sBwze-hobrbmdEhvivwKITijj85WKWSqM/gviz/tq?tqx=out:csv&range=D1:E21&sheet=hoja1";
		
// Descargar los datos del rango 1
$datos_rango1 = file_get_contents($url_rango1);
$filas_rango1 = str_getcsv($datos_rango1, "\n");

// Descargar los datos del rango 2
$datos_rango2 = file_get_contents($url_rango2);
$filas_rango2 = str_getcsv($datos_rango2, "\n");

// Unir los datos de ambos rangos
$datos_unidos = "";
for ($i = 0; $i < count($filas_rango1); $i++) {
    $datos_unidos .= $filas_rango1[$i] . "," . $filas_rango2[$i] . "\n";
}

// Imprimir los datos unidos
$datos_unidos  = rtrim($datos_unidos, "\n"); // Elimina último \n
$datos_unidos = str_replace('"', '', $datos_unidos); // Elimina "
 ?>
 
  Click on a header.<br><br>
  <div id="table-container"></div>

  <script>
 // var string = "Fernando,33,Granada,04\nAntonio,66,Sevilla,03\nLuis,55,Cádiz,02\nCarlos,44,Córdoba,01\nRicardo,77,Huelva,05";
    var string = <?php echo json_encode($datos_unidos);
	?>;

var rows = string.split("\n");
var table = document.createElement("table");
var ascending = true;

var headerRow = document.createElement("tr");
var headerCell1 = document.createElement("th");
var headerCell2 = document.createElement("th");
var headerCell3 = document.createElement("th");
var headerCell4 = document.createElement("th");
headerCell1.appendChild(document.createTextNode("Column 1"));
headerCell2.appendChild(document.createTextNode("Column 2"));
headerCell3.appendChild(document.createTextNode("Column 3"));
headerCell4.appendChild(document.createTextNode("Column 4"));

// Agregar atributos data-sort-type a cada celda del encabezado
headerCell1.setAttribute("data-sort-type", "asc");
headerCell2.setAttribute("data-sort-type", "asc");
headerCell3.setAttribute("data-sort-type", "asc");
headerCell4.setAttribute("data-sort-type", "asc");

// Agregar event listener a cada celda del encabezado
headerCell1.addEventListener("click", function() { sortTable(0); });
headerCell2.addEventListener("click", function() { sortTable(1); });
headerCell3.addEventListener("click", function() { sortTable(2); });
headerCell4.addEventListener("click", function() { sortTable(3); });

headerRow.appendChild(headerCell1);
headerRow.appendChild(headerCell2);
headerRow.appendChild(headerCell3);
headerRow.appendChild(headerCell4);
table.appendChild(headerRow);

for (var i = 0; i < rows.length; i++) {
  var cols = rows[i].split(",");
  var row = document.createElement("tr");
  if (i % 2 == 0) {
    row.style.backgroundColor = "#d1f0d1";
  } else {
    row.style.backgroundColor = "#ffdede";
  }
  for (var j = 0; j < cols.length; j++) {
    var cell = document.createElement("td");
    cell.appendChild(document.createTextNode(cols[j]));
    row.appendChild(cell);
  }
  row.addEventListener("click", function() {
    var rowContent = "";
    for (var k = 0; k < this.cells.length; k++) {
      rowContent += this.cells[k].innerHTML + "|";
    }
    alert(rowContent);
  });
  table.appendChild(row);
}

document.getElementById("table-container").appendChild(table);

function sortTable(columnIndex) {
  var rows = Array.from(table.rows).slice(1); // exclude header row
  rows.sort(function(rowA, rowB) {
    var cellA = rowA.cells[columnIndex].textContent.trim();
    var cellB = rowB.cells[columnIndex].textContent.trim();

if (cellA.localeCompare(cellB, 'es', { sensitivity: 'base' }) < 0) {
  return ascending ? -1 : 1;
} else if (cellA.localeCompare(cellB, 'es', { sensitivity: 'base' }) > 0) {
  return ascending ? 1 : -1;
} else {
  return 0;
}
  });


  for (var i = table.rows.length - 1; i >= 1; i--) {
    table.deleteRow(i);
  }
  
  // re-insert sorted rows
  for (var i = 0; i < rows.length; i++) {
   var row = rows[i];
  // alternar color de fondo de la fila
  if (i % 2 == 0) {
		row.style.backgroundColor = "#d1f0d1";
	  } else {
		row.style.backgroundColor = "#ffdede";
	  }

  table.appendChild(row);
  }

  // toggle sort direction for next click
  ascending = !ascending;
}
  </script>
</body>
</html>

http://kio4.com/appinventor/php/googlesheet5.php

You should be able to do it with just one url call....

.../gviz/tq?tqx=out:csv&sheet=hoja1&range=A1:E21&tq=SELECT A,B,D,E

9.- Sort table. Google Sheet. JavaScript.

  • Now with JavaScript in a web page.
  • The data is in Google Sheet.

http://kio4.com/appinventor/php/googlesheet8.htm

googlesheet8.htm
<!DOCTYPE html>
<html>
<head>
  <title>Tabla de Datos</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0">
    <style>
    table {
      border-collapse: collapse;
      width: 100%;
      max-width: 800px;
      margin: 0 auto;
    }
    th, td {
      padding: 8px;
      text-align: center;
      border: 1px solid #000;
      cursor: pointer;
    }
    th {
      background-color: #f2f2f2;
    }
    tr:nth-child(even) {
      background-color: #d1f0d1;
    }
    tr:nth-child(odd) {
      background-color: #ffdede;
    }
  </style>
</head>
<body>
<div id="table-container"></div>

  <script>
// Obtener los datos de la hoja de cálculo y almacenarlos en la variable "datos"
var url = 'https://docs.google.com/spreadsheets/d/1M9Tfz0O1a0sBwze-hobrbmdEhvivwKITijj85WKWSqM/gviz/tq?tqx=out:csv&sheet=hoja1&range=A1:E21&tq=SELECT%20A,B,D,E';
var datos = '';
var ascending = true;

// Realizar la solicitud HTTP GET utilizando XMLHttpRequest
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.onreadystatechange = function() {
  if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
	datos = xhr.responseText;

	var string = datos;
	var rows = string.split("\n");
	var table = document.createElement("table");
	var ascending = false;

var headerRow = document.createElement("tr");
var headerCell1 = document.createElement("th");
var headerCell2 = document.createElement("th");
var headerCell3 = document.createElement("th");
var headerCell4 = document.createElement("th");
headerCell1.appendChild(document.createTextNode("Column 1"));
headerCell2.appendChild(document.createTextNode("Column 2"));
headerCell3.appendChild(document.createTextNode("Column 3"));
headerCell4.appendChild(document.createTextNode("Column 4"));

// Agregar atributos data-sort-type a cada celda del encabezado
headerCell1.setAttribute("data-sort-type", "asc");
headerCell2.setAttribute("data-sort-type", "asc");
headerCell3.setAttribute("data-sort-type", "asc");
headerCell4.setAttribute("data-sort-type", "asc");

// Agregar event listener a cada celda del encabezado
headerCell1.addEventListener("click", function() { sortTable(0); });
headerCell2.addEventListener("click", function() { sortTable(1); });
headerCell3.addEventListener("click", function() { sortTable(2); });
headerCell4.addEventListener("click", function() { sortTable(3); });

headerRow.appendChild(headerCell1);
headerRow.appendChild(headerCell2);
headerRow.appendChild(headerCell3);
headerRow.appendChild(headerCell4);
table.appendChild(headerRow);

	for (var i = 0; i < rows.length; i++) {
	  var cols = rows[i].split(",");
	  var row = document.createElement("tr");
	  if (i % 2 == 0) {
		row.style.backgroundColor = "#d1f0d1";
	  } else {
		row.style.backgroundColor = "#ffdede";
	  }
	  for (var j = 0; j < cols.length; j++) {
		var cell = document.createElement("td");
		cell.appendChild(document.createTextNode(cols[j]));
		row.appendChild(cell);
	  }
	  row.addEventListener("click", function() {
		var rowContent = "";
		for (var k = 0; k < this.cells.length; k++) {
		  rowContent += this.cells[k].innerHTML + "|";
		}
		alert(rowContent);
	  });
	  
	 // Crear las celdas iniciales sin comillas dobles
    for (var j = 0; j < row.cells.length; j++) {
      var cell = row.cells[j];
      cell.textContent = cell.textContent.replace(/"/g, '');
    }
	  
	  table.appendChild(row);
	}

	document.getElementById("table-container").appendChild(table);
  }
};
xhr.send();

function sortTable(columnIndex) {
  var table = document.querySelector("table");
  var rows = Array.from(table.rows).slice(1); // exclude header row
  ascending = !ascending;  // Cambiar la dirección de ordenamiento.

  rows.sort(function(rowA, rowB) {
	var cellA = rowA.cells[columnIndex].textContent.trim();
	var cellB = rowB.cells[columnIndex].textContent.trim();

  if (cellA.localeCompare(cellB, 'es', { sensitivity: 'base' }) < 0) {
  return ascending ? -1 : 1;
} else if (cellA.localeCompare(cellB, 'es', { sensitivity: 'base' }) > 0) {
  return ascending ? 1 : -1;
} else {
  return 0;
}
  });

  for (var i = table.rows.length - 1; i >= 1; i--) {
	table.deleteRow(i);
  }
  
  // Re-insertar filas ordenadas
  for (var i = 0; i < rows.length; i++) {
	var row = rows[i];
	
	// Alternar color de fondo de la fila
	if (i % 2 == 0) {
	  row.style.backgroundColor = "#d1f0d1";
	} else {
	  row.style.backgroundColor = "#ffdede";
	}
	
	 // Crear las celdas actualizadas sin comillas dobles
    for (var j = 0; j < row.cells.length; j++) {
      var cell = row.cells[j];
      cell.textContent = cell.textContent.replace(/"/g, '');
    }

	table.appendChild(row);
  }
}
  </script>
</body>
</html>

p170F_JavaScriptTablaCSS_v5.aia (3.4 KB)

(*) OK @TIMAI2, here i used: ...sheet=hoja1&range=A1:E21&tq=SELECT%20A,B,D,E';

1 Like