Making a table based of user input - javascript

<input type="number" id="arrayLength" />
<button id="myButton">Submit</button>
<table id="finalTable"></table>
var tableData = ["<td>"];
function myFunction(){
var tableRow;
tableData.length = document.getElementById("arrayLength").value;
for(i=0; i<tableData.length; i++){
tableData[i] = "This is your table";
tableRow = "<tr>" + tableData[i] + "</tr>";
}
return tableRow;
}
document.getElementById("myButton").onclick = function(){
document.getElementById("finalTable").innerHTML = myFunction();
}
Here what I want, when a user input some number in field, it should create a table with same rows & with data "this is your table" in it. I mean if I input 5, it should make 5 rows & 5 columns with "this is your table" in each cell. Currently it's making only one cell. I know it's far away from desired output, but please help me. Thanks in advance.

The reason you are only getting 1 cell, is because you are assigning to tableRow instead of concatenating. Also, you might want to use a nested for loop, to add columns as well as rows:
function myFunction()
{
var tableRow = ""; //Give a default value here
var length = document.getElementById("arrayLength").value;
for(i=0; i<length; i++){
tableRow += "<tr>";
for(j=0; j<length; j++)
{
tableRow += "<td>";
tableRow += "This is your table";
tableRow += "</td>";
}
tableRow += "</tr>";
}
return tableRow;
}
And here's where I tested it, to make sure it works: http://jsfiddle.net/k8dxqu6h/

You are overwriting tableRow with every iteration. Concatenate, don't assign.
tableRow += "<tr>" + tableData[i] + "</tr>";
^

Related

GAS dynamically HTML table created with radiobutton in each row, trying to assign an id to each radiobutton in each row by using a variable name

I have a GAS google apps script web app that has a search box and a button, when clicked, it dynamically loads an HTML table using the input of the user from the previous searchbox, and looks up some data from a google spreadsheet and returns an html table with 3 to 5 rows. the table is created correctly,the first column has only radiobuttons, the second third and 4th has other fields about each user. all of the radiobuttons have the same name i.e. "choiceSelectionRadio", thus they are grouped and only one of them can be selected at once. however, for the next step (posting the information back to the spreadsheet) i need to succesfully identify which radiobutton, and accordingly, which row has the user selected, and for identifying the radiobuttons i need to assign them an id. I tried to name their id by using the count variable in the FOR LOOP, but it is not working. no errors from the console but no assignment so far.
Here is the function i have.
function crearTabla(arrayDatos) {
//si el array de datos es diferente a indefinido y su longitud es diferente a cero
if(arrayDatos && arrayDatos !== undefined && arrayDatos.length != 0){
var tablaResultados = "<table class='table table-sm table-striped' id='dtable' style='font-size:0.8em'>"+
"<thead style='white-space: nowrap'>"+
"<tr>"+
"<th scope='col'>LOTE</th>"+
"<th scope='col'>OP PI</th>"+
"<th scope='col'>CODIGO PI</th>"+
"<th scope='col'>NOMBRE PROD INTERM</th>"+
"<th scope='col'>CANTIDAD (LX)</th>"+
"<th scope='col'>CONVERSION</th>"+
"<th scope='col'>FECHA USAR EN PLANTA</th>"+
"<th scope='col'>CODIGO PT</th>"+
"<th scope='col'>DESCRIPCION</th>"+
"<th scope='col'>SELECCIONADO?</th>"+
"</tr>"+
"</thead>";
//FIRST LOOP: create as many rows as the filtered range in the sheet has
for(var fila=0; fila<arrayDatos.length; fila=fila+1) {
tablaResultados = tablaResultados + "<tr>";
//SECOND LOOP: in each row created, populate with the information filtered
for(var col=0; col<arrayDatos[fila].length+1; col=col+1){
//NOTE: using lenght+1 since i want a final column for placing the radiobuttons
//tablaResultados = tablaResultados + "<td>"+arrayDatos[fila][col]+"</td>";//do loop en each array value
if (col==arrayDatos[fila].length){tablaResultados = tablaResultados + "<td>"+"<input type='radio' name='chooseLote' id='fila'>"+"</td>"} //HERE IS THE PROBLEM************************************************************************
else{
tablaResultados = tablaResultados + "<td>"+arrayDatos[fila][col]+"</td>";//do loop en each array value
}
}
tablaResultados = tablaResultados + "</tr>";
}
tablaResultados = tablaResultados + "</table>";
var div = document.getElementById('espacioParaTablaResultados');
div.innerHTML = tablaResultados;
}else{
var div = document.getElementById('espacioParaTablaResultados');
//div.empty()
div.innerHTML = "No se encontraron coincidencias";
}
}
I prefer to use DOM. This is how I would do it. The reason I prefer DOM is because to achieve this with writing html would require concatination of strings to get the complete html tag. And its easier to add attributes to an html element.
First I would include the table with header in the body of the html page with an id. In this case "myTable".
Then I would get the data from the spreadsheet getData() or this could be done through templated html.
Then I create a radio button in the first column. I assign a value equal to the row it is on.
Then I have a "Submit" button to identify which of the radio buttons has been selected.
My spreadsheet looks like this.
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<table id="myTable">
<input id="selectButton" type="button" value="Select" onclick="selectOnClick()">
<tr>
<th>Button</th>
<th>Id</th>
<th>Name</th>
<th>Date</th>
</tr>
</table>
<script>
function selectOnClick() {
let table = document.getElementById("myTable");
for( let i=1; i<table.rows.length; i++ ) { // skip header row
let row = table.rows[i];
let cell = row.cells[0];
if( cell.firstChild.checked ) {
alert(cell.firstChild.value);
return;
}
}
}
function createRow(i,data) {
let table = document.getElementById("myTable");
let row = document.createElement("tr");
let cell = document.createElement("td");
let button = document.createElement("input");
button.setAttribute("type", "radio");
button.setAttribute("name", "radioGroup");
button.setAttribute("value",i+1);
cell.appendChild(button);
row.appendChild(cell);
data.forEach( value => {
let text = document.createTextNode(value);
cell = document.createElement("td");
cell.appendChild(text);
row.appendChild(cell);
}
)
table.appendChild(row);
}
(function() {
google.script.run.withSuccessHandler(
function (data) {
for( let i=0; i<data.length; i++ ) {
createRow(i+1,data[i]);
}
}
).getData();
})();
</script>
</body>
</html>
When the page is displayed it looks like this. And if I select a radio button and press the select button a dialog is displayed.
Perhaps this will work for you:
function crearTabla(datA) {
if (datA && datA !== undefined && datA.length !== 0) {
var tblres = "<table class='table table-sm table-striped' id='dtable' style='font-size:0.8em'>" +
"<thead style='white-space: nowrap'>" +
"<tr>" +
"<th scope='col'>LOTE</th>" +
"<th scope='col'>OP PI</th>" +
"<th scope='col'>CODIGO PI</th>" +
"<th scope='col'>NOMBRE PROD INTERM</th>" +
"<th scope='col'>CANTIDAD (LX)</th>" +
"<th scope='col'>CONVERSION</th>" +
"<th scope='col'>FECHA USAR EN PLANTA</th>" +
"<th scope='col'>CODIGO PT</th>" +
"<th scope='col'>DESCRIPCION</th>" +
"<th scope='col'>SELECCIONADO?</th>" +
"</tr>" +
"</thead>";
for (var i = 0; i < datA.length; i++) {
tblres = tblres + "<tr>";
for (var j = 0; j < datA[i].length + 1; j++) {
tblres = tblres + "<td>" + datA[i][j] + "</td>";
}
tblres = tblres + "<td>" + "<input type='radio' name='chooseLote' id='fila'>" + "</td>"
}
tblres = tblres + "</tr>";
}
tblres = tblres + "</table>";
//I lost track of what was going on down here. I hate everything
not being in English sorry.
}

using jquery to append rows from sql, resulting all rows appended in thead first td

I was going to use jquery to append rows from sql, but resulting all rows appended in thead first td.
enter image description here
and the code is
<body>
<table id="table">
<thead><td>A</td><td>B</td><td>C</td><td>D</td><td>E</td><td>F</td><td>G</td></thead>
</table>
</body>
</html>
<script>
$(document).ready(function(){
var sql = "select*from test";
$.ajax({
url:"query.php",
data:{
sqls:sql
},
async:false,
success:function(data){
var returned_data = JSON.parse(data);
for(var i=0;i<returned_data.length;i++){
var temp_str = "<tr class='row'>";
temp_str += "<td class='cell'>";
temp_str += "<input class='cell_vale' type='text' value='";
temp_str += returned_data[i]['firstcell']+"'>";
temp_str += "</td>";
... the other 5 cells is same ...
temp_str += "</tr>";
$("table").append(temp_str);
}
}
});
});
</script>
I tried to use tbody but failed,
also tried to remove thead,
but after it the table width will not suit to the cells,
if there are many cells in a row, the cells may display in 2 rows but one tr.
Can anyone help me?Thanks
First of all, I would suggest going over the modern approach of data binding for much easier and cleaner implementations of what you're trying to do. Have a look at VueJS or React, they will certainly help you big time!
Secondly, try moving your temp_str and row appendage outside of the for..loop, like so
var returned_data = [
{ firstcell: 'cell1' },
{ firstcell: 'cell2' },
{ firstcell: 'cell3' }
];
var temp_str = "";
for(var i = 0; i < returned_data.length; i++) {
temp_str += "<tr class='row'>";
temp_str += "<td class='cell'>";
temp_str += "<input class='cell_vale' type='text' value='";
temp_str += returned_data[i]['firstcell'] + "'>";
temp_str += "</td>";
temp_str += "</tr>";
}
$("table").append(temp_str);
And see if it works for you?

javascript to create table php mysql to save data

I need a table where the user enters how many rows and columns needed, they enter the numbers and the next page creates the table.
They will enter the info which will be saved into a database. The only way I can think to do this is with dynamic tables, is there a better way? Here is some super basic code, I haven't worked out the full table, wanted to get feedback before I continue in case there is a better way and I need to change course.
Simple form:
How many rows <input type="number" id="rowNumber"/><br>
How many columns <input type="number" id="colNumber"/><br>
<button onclick="myFunction()">Checkout</button>
function myFunction() {
var rowNumber = document.getElementById('rowNumber').value;
var colNumber = document.getElementById('colNumber').value;
window.location.href = "website/test.php?rowNumber="+rowNumber+"&colNumber="+colNumber;
}
test.php
<?php
$rowNumber=$_GET['rowNumber'];
$colNumber=$_GET['colNumber'];
?>
<script>
var numRows = "<? echo $rowNumber ?>";
var numCols = "<? echo $colNumber ?>";
var tableString = "<table>",
body = document.getElementsByTagName('body')[0],
div = document.createElement('div');
for (row = 1; row < numRows; row += 1) {
tableString += "<tr onclick=\"fnselect(this)\"<? if($rowID == "A") { echo "class ='selected'";} ?>>";
for (col = 1; col < numCols; col += 1) {
tableString += "<td>" + "R" + row + "C" + col + "" + "<input type='text' />" + "</td>";
}
tableString += "</tr>";
}
tableString += "</table>";
div.innerHTML = tableString;
body.appendChild(div);
</script>
Looking into jQuery DataTables. A lot of nice functionality in there.
You can either bind to a JSON data source, or create your own rows manually like this URL:
https://datatables.net/examples/api/add_row.html
So, to use this, you have to reference jquery AND the data tables script. You'll have to either reference them from their given URLs, or download the scripts (I recommend the latter otherwise you create references to outside servers).

How to get the value of dynamically created tablerow?

I tried to get the value of the input-field that was dynamically created in function rijToevoegen().
Somehow I keep getting undefined, what am I doing wrong?
These are my functions I use:
//adding the tablerow
function rijToevoegen(columnarray, fieldarray, tabelnaam){
var columns = columnarray;
var fields = fieldarray;
var row = '<tr>';
for(i=0;i<columns.length;i++){
row += "<td class=columns[i]><input type='text' id=fields[i]></td>";
console.log(fields[i]);
}
row += '</tr>';
$(tabelnaam).append(row);
}
//getting the value
$('#vs_opslaan').click(function() {
var columns = ['naamkolom','locatiekolom','hostkolom','cpukolom','memorykolom','oskolom','hddkolom','spkolom','usernamekolom','passwordkolom','ipkolom','domeinkolom','opmerkingenkolom'];
var velden = ['naamveld','locatieveld','hostveld','cpuveld','memoryveld','osveld','hddveld','spveld','usernameveld','passwordveld','ipveld','domeinveld','opmerkingenveld'];
var response_array = [];
for(i=0;i<velden.length;i++){
var rij = $('#velden[i]').val();
console.log(rij);
//response_array += $().value;
}
//console.log(response_array);
});
Help is always appreciated!
Ramon
When you are referencing the arrays they cannot be inside the string or they will be set as literal strings.
When you put "<td class=columns[i]><input type='text' id=fields[i]></td>"the class and id contain literal strings columns[i] and fields[i]
What you want is to concatenate your array values with the markup.
"<td class=" + columns[i] + "><input type='text' id=" + fields[i] + "></td>"
This also applies to when you are doing the jquery selector.
So instead of $('#velden[i]').val(); you want $('#' + velden[i]).val();

Print a table inside a div with given row and column via Javascript

I have two textfield and one button. When user clicked the button, It calls a function and print a table inside a div with given number of rows and columns.
You can see my code below, but this is not working as expected.
HTML
Rows <input type="text" id="rows">
Columns <input type="text" id="columns">
<input type="button" value="Create Table" onClick="printTable();">
<div id="box"></div>
Javascript
function printTable()
{
var nRows=document.getElementById("rows");
var nColumns=document.getElementById("columns");
var spaceofDiv=document.getElementById("box");
spaceofDiv.innerHTML=("<table border=1>");
for(i=0; i<nRows.value; i++)
{
spaceofDiv.innerHTML=("<tr>");
for(j=0; j<nColumns.value; j++)
{
spaceofDiv.innerHTML=("<td width=50 height=50> ");
}
}
spaceofDiv.innerHTML=("</table>");
}
You need to remember to
A) Close your table row and table cell elements
B) Concatenate the value of the table markup, as you are currently overwriting your changes with each assignment
var markup = '';
markup = "<table border=1>";
for(i=0; i<nRows.value; i++)
{
markup += "<tr>";
for(j=0; j<nColumns.value; j++)
{
markup += "<td width=50 height=50> </td>";
}
markup += "</tr>";
}
markup = "</table>";
spaceofDiv.innerHTML = markup;
Try some thing this. Use a avariable add all string in to it and then set innerhtml. Als oyou are not closing the tr
function printTable()
{
var nRows=document.getElementById("rows");
var nColumns=document.getElementById("columns");
var spaceofDiv=document.getElementById("box");
var tableStr = "";
tableStr =("<table border=1>");
for(i=0; i<nRows.value; i++)
{
tableStr +="<tr>";
for(j=0; j<nColumns.value; j++)
{
tableStr +="<td width=50 height=50></td> ";
}
tableStr +="</tr>";
}
tableStr += "</table>"
spaceofDiv.innerHTML=tableStr;
}

Categories

Resources