Converting CSV input in textarea to dynamic table - javascript

This picture defines what I need
I want that the data I enter dynamically to be converted to table with each comma defining the column and the newline defining the new row.
Below is the code I have tried. Can I have a better approach to this problem?
<script>
function myFunction()
{
var x = document.getElementById("textarea").value.split(" ");
var customers = new Array();
customers.push(x[0]);
customers.push(x[1]);
customers.push(x[2]);
var table = document.createElement("TABLE");
table.border = "1";
//Get the count of columns.
var columnCount = customers[0].length;
//Add the header row.
var row = table.insertRow(-1);
for (var i = 0; i < columnCount; i++) {
var headerCell = document.createElement("TH");
headerCell.innerHTML = customers[0][i];
row.appendChild(headerCell);
}
//Add the data rows.
for (var i = 1; i < customers.length; i++) {
row = table.insertRow(-1);
for (var j = 0; j < columnCount; j++) {
var cell = row.insertCell(-1);
cell.innerHTML = customers[i][j];
}
}
var dvTable = document.getElementById("dvTable");
dvTable.innerHTML = "";
dvTable.appendChild(table);
}
</script>
<html>
<head>
<title>Player Details</title>
</head>
<body align = "center">
<h3 align = "center"><b>Input CSV</b></h3>
<p align = "center"><textarea rows="10" cols="50" name = "csv" id = "textarea"></textarea></p><br>
<button type="button" id = "convert" onclick="myFunction()">Convert</button><br>
<br>
<div id = "team"></div>
</body>
</html>

You need to split the data first using newline (\n) and then using comma (,) character.
The table can be created as string and finally inserted to the correct div.
Refer the code below to get you started.
function myFunction() {
var tbl = "<table class='table table-responsive table-bordered table-striped'><tbody>"
var lines = document.getElementById("textarea").value.split("\n");
for (var i = 0; i < lines.length; i++) {
tbl = tbl + "<tr>"
var items = lines[i].split(",");
for (var j = 0; j < items.length; j++) {
tbl = tbl + "<td>" + items[j] + "</td>";
}
tbl = tbl + "</tr>";
}
tbl = tbl + "</tbody></table>";
var divTable = document.getElementById('team');
console.log(tbl);
divTable.innerHTML = tbl;
}
I've used bootstrap for css, you may want to use your own (or not).
Refer jsFiddle here.

Related

Creating button in modal dialogue and run code in spreadsheet

I making a table and show it in the modal dialogue so that buttons will appear for each row in the table. My question is how to make the button in the modal dialogue run for specific row in spreadsheet? Example : click first button in first row in modal dialogue, will run and change data in first row of spreadsheet. Do I need to create specific ID for each buttons?
My GS code:
function leadRespond(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Query_Script");
var dataRange = sheet.getDataRange();
var dataValue = dataRange.getDisplayValues();
var temp = HtmlService.createTemplateFromFile("lead");
temp.data = {application : dataValue};
var html = temp.evaluate().setWidth(1200).setHeight(600);
SpreadsheetApp.getUi().showModalDialog(html,"Manage Leave");
}
HTML code:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<h1>Leave Application</h1>
<div id="output"></div>
<script>
var output = document.getElementById("output");
window.onload = function (){
google.script.run.withSuccessHandler(onSuccess).getTable();
}
function onSuccess(data){
if(data.success){
console.log(data.data);
var html = '<table>';
var row;
for(var i=0; i<data.data.length; i++){
html += '<tr>';
row = i;
//console.log(row);
for (var j=0; j<9; j++){
html += '<td>'+ data.data[i][j]+'</td>';
}
html += '<td>'+ '<button onclick="approve()">Approved</button>'+'</td>';
html += '</tr>';
}
html += '</table>';
output.innerHTML = html;
console.log(data);
}
}
function approve(){
google.script.run.getRow();
console.log("test");
}
</script>
</body>
</html>
Code with google.script.run :
function getTable(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Query_Script");
var data = sheet.getDataRange().getDisplayValues();
Logger.log(data);
return {'success': true,'data':data};
}
function getRow(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Query_Script");
for (var i=0; i<dataValue.length; i++){
var row = "";
var rowNum;
for (var j = 0; j < 9; j++) {
if (dataValue[i][j]) {
row = row + dataValue[i][j]; //row = "" + range(0,0) [emailAddress], row = range(0,0)+ range(0,1)[emailAddress,Timestamp]
}
row = row + ",";
}
row = row + " Row num " + i;
rowNum = i;
Logger.log(row);
Logger.log(rowNum);
}
}
Use custom html-data attributes and delegate event to <table>:
html += '<td>'+ '<button data-row="'+i+'" data-column="'+j+'">Approved</button>'+'</td>';
//...
output.innerHTML = html;
console.log(data);
const table = document.querySelector("table");
table.addEventListener('click', approve);
}
function approve(e){
const td = e.target;
const [row, column] = [td.dataset.row,td.dataset.column];
google.script.run.modifyRows(row,column);
}

Table Issue in WYSIWYG Editor

I'm creating an HTML WYSIWYG editor from scratch and I have an issue when it comes to tables. Somehow, I'm able to create the pretended number of columns but only one row (without the heading). I'd be thankful if anyone could tell what's the issue.
HTML
<!DOCTYPE html>
<html>
<head>
<title>Text Editor</title>
</head>
<body>
<div id="Ribbon">
<div id="Ribbon-3">
<button class="RibbonBtn" id="TableButton" title="Insert Table"><i class="fas fa-table"></i></button>
</div>
</div>
<div id="TextArea">
<div id="WYSIWYG" contenteditable="true"></div>
</div>
</div>
</body>
</html>
JS
window.addEventListener("load",function(){
$('#TableButton').click(function(){
var colnum = prompt("Indicate the number of columns");
var rownum = prompt("Indicate the number of rows");
var table = "";
var tablehead = "";
var tablebodytext = "";
for (var i = 0; i < colnum; i++) {
tablehead += "<th>null</th>";
}
var tablebody = [];
for (var i = 0; i < rownum; i++) {
var tablebodyrow = "";
for (var i = 0; i < colnum; i++) {
tablebodyrow += "<td>null</td>";
}
tablebody += "<tr>" + tablebodyrow + "</tr>";
}
table = "<table><tr>" + tablehead + "</tr>" + tablebody+ "</table>";
document.execCommand("insertHTML",false, table);
});
},false);
I chose 5 columns and 4 rows, but instead it created 5 columns and only 1 row
I've found the error. Such a dumb mistake...
I was using the same "i" var for the nested for loop and its parent loop.
This is the right version:
$('#TableButton').click(function(){
var colnum = prompt("Indicate the number of columns:");
var rownum = prompt("Indicate the number of rows:");
var table = "";
var tablehead = "";
var tablebodytext = "";
for (var i = 0; i < colnum; i++) {
tablehead += "<th>null</th>";
}
var tablebody = [];
for (var i = 0; i < rownum; i++) {
var tablebodyrow = "";
for (var i1 = 0; i1 < colnum; i1++) {
tablebodyrow += "<td>null</td>";
}
tablebody += "<tr>" + tablebodyrow + "</tr>";
}
table = "<table><tr>" + tablehead + "</tr>" + "<tbody>" + tablebody + "</tbody>" + "</table>";
document.execCommand("insertHTML",false, table);
});

Assign Id and iterate through rows in Javascript

I created a table, which seems to work fine, but I have problems assigning an id to this table, count how many rows it has, and assign each row an id. The debugger says:
TypeError: document.getElementById(...) is null
I couldn't figure out what I did wrong. Can someone please help? I commented my questions in the code below as well:
function populateTable(list){
var tableContent = "<table>";
for (var i = 0; i < list.length; ++i) {
var record = list[i];
tableContent += "<tr><td>" + record.Title + "</td></tr>\n";
}
tableContent += "</table>";
tableContent.id="orders";
var rows = document.getElementById("orders").rows.length;//why is this null?
document.getElementById("test").innerHTML = rows;
for (var i=0; i< rows; ++i){
//how do I assign an id for the element here?
}
}
You can do this in this way:
HTML:
<div id="here"> </div> <!-- the table will be added in this div -->
JavaScript:
function populateTable(list){
var tableContent = document.createElement('table');
for (var i = 0; i < list.length; ++i) {
var record = list[i];
var cell = document.createElement('td');
var row = document.createElement('tr');
var textnode = document.createTextNode(record.Title);
cell.appendChild(textnode);
row.appendChild(cell);
tableContent.appendChild(row);
}
tableContent.id="orders";
document.getElementById("here").appendChild(tableContent); // the table is added to the HTML div element
var rows = document.getElementById("orders").rows;
for (var i=0; i < rows.length; ++i){
rows[i].id = "myId" + (i+1); // this is how you assign IDs
console.log(rows[i]);
}
}
var persons = [{Title:"John"}, {Title:"Marry"}];
populateTable(persons);
Edit
It seems you don't know how to properly create a DOM from javascript:
http://www.w3schools.com/jsref/met_document_createelement.asp
Old answer
This line:
var rows = document.getElementById("orders").rows.length;//why is this null?
Get elements from HTML document by id. And it looks like you have not added tableContent yet to the document.
Here's my suggestion (read the comments in the code):
// This will create a table element and return it
function createTable(list){
var table = document.createElement('table'); // This is an actual html element
table.id = 'orders'; // Since it's an html element, we can assign an id to it
tableHtml = ''; // This empty string will hold the inner html of the table we just created
for (var i = 0; i < list.length; ++i) {
var record = list[i];
// we can assign the id here instead of looping through the rows again
tableHtml += '<tr id="row-' + i + '"><td>' + record.Title + '</td></tr>';
}
table.innerHTML = tableHtml; // We insert the html into the table element and parse it
var rows = table.rows.length; // We already have a reference to the table, so no need of getElementById
alert('rows'); // rows holds the number of rows. You can do whatever you want with this var.
return table; // return the table. We still need to insert it into the dom
}
// Create a new table and hold it in memory
var myTable = createTable([{Title:'One'}, {Title:'Two'}, {Title:'Three'}]);
// Inset the newly created table into the DOM
document.getElementById('parent-of-table').appendChild(myTable);
Hope this helps
This is already been answered, but here's my version without all the comments:
function createTable(list){
var table = document.createElement('table');
table.id = 'orders';
tableHtml = '';
for (var i = 0; i < list.length; ++i) {
tableHtml += '<tr id="row-' + i + '"><td>' + list[i].Title + '</td></tr>';
}
table.innerHTML = tableHtml;
var rows = table.rows.length;
alert('rows');
return table;
}

How to read value of Textbox which is inside table

I need to read the value of textbox which is inside the table.
Following is how I create table.
var theader = '<table border = "1" id = "MarksTable">\n';
var tbody = '';
for ( var i = 0; i < total_rows; i++) {
tbody += '<tr>';
for ( var j = 0; j < total_col; j++) {
tbody += '<td name=' + "cell" + i + j + '>';
if (i > 0) {
tbody += '<input type="text" value = "marks" name="inputcell1'+j + '">';
} else {
tbody += '<b>' + subjectList[j] + '</b>';
}
tbody += '</td>';
}
tbody += '</tr>\n';
}
var tfooter = '</table>';
document.getElementById('wrapper').innerHTML = theader
+ tbody + tfooter ;
and below is my attempt to read text box value:
function readTableData(){
var marks = [];
var table = document.getElementById("MarksTable");
var column_count = table.rows[1].cells.length;
var row = table.rows[1];
if(column_count>0){
for(var index = 0; index < column_count;index++){
marks[index] = row.cells[index].innerHTML;
}
}
return marks;
}
Here, row.cells[index].innerHTML gives the output '<input type="text" value = "marks" name="inputcell10">.
Try this:
function readTableData(){
var marks = [];
var table = document.getElementById("MarksTable");
var column_count = table.rows[1].cells.length;
var row = table.rows[1];
if(column_count>0){
for(var index = 0; index < column_count;index++){
marks[index] = row.cells[index].getElementsByName('inputcell' + index)[0].value;
//Or marks[index] = document.getElementsByName('inputcell' + index)[0].value;
}
}
return marks;
}
<!DOCTYPE html>
<html>
<head>
<style>
table, td {
border: 1px solid black;
}
</style>
</head>
<body>
<p>Click the button to add a new row at the first position of the table and then add cells and content.</p>
<div id="tableContainer">
</div>
<br>
<button onclick="myFunction()">Try it</button>
<button onclick="readTableData()"> Read it </button>
<script>
function myFunction() {
var tab = '<table id="MarksTable">';
var counter = 0;
for(i = 0; i< 4; i++){
tab = tab + '<tr><td rowspan = "4"> Dept1 </td><td> <input type="text" id="inputcell'+counter+'" value="'+i+'"/> </td></tr>';
counter++;
tab = tab+'<tr><td> <input type="text" id="inputcell'+counter+'" value="'+i+'"/> </td></tr>';
counter++;
tab = tab+'<tr><td> <input type="text" id="inputcell'+counter+'" value="'+i+'"/> </td></tr>';
counter++;
tab = tab+'<tr><td> <input type="text" id="inputcell'+counter+'" value="'+i+'"/> </td></tr>';
counter++;
}
tab = tab + '</table>';
document.getElementById("tableContainer").innerHTML = tab;
}
function readTableData(){
var val;
var table = document.getElementById("MarksTable");
var column_count = table.rows[1].cells.length;
var rowcount = table.rows.length;
alert(rowcount);
if(column_count>0){
for(var index = 0; index < rowcount;index++){
var row = table.rows[index];
val = document.getElementById("inputcell"+index);
alert(val.value);
//marks = row.cells[0].getElementsByName('inputcell').value;
//Or marks[index] = document.getElementsByName('inputcell' + index)[0].value;
}
}
alert(val);
}
</script>
</body>
</html>

JavaScript onclick programaticly not always works

I'm trying to set a onclick event handler.
from some reason this works:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript">
function init() {
var td = document.getElementById("td");
var table = document.createElement("table");
var row = table.insertRow(0);
var cell = row.insertCell(0);
cell.innerHTML = "test";
cell.onclick = function () { alert(); };
td.appendChild(table);
}
</script>
</head>
<body id="td" onload="init()">
</body>
</html>
and when putting it in outside js file it doesn't work:
function buildChessBoard() {
var currentColor = white;
//var table = "<table>";
var table = document.createElement("table");
for (var i = 0; i < chessBoardsize / 8; i++) {
//table += "<tr>";
var row = table.insertRow(i);
for (var j = 0; j < 8; j++) {
//table += "<td class=" + currentColor + "Cell" + " id=" + (i * 8 + j) + " onclick=setCell(this)></td>";
var cell = row.insertCell(j);
cell.innerHTML = "test";
cell.onclick = function () { alert(); };
if (j != 7) {
if (currentColor == white)
currentColor = gray;
else
currentColor = white;
}
}
//table += "</tr>";
}
//table += "</table>";
//chessBoardDiv.innerHTML = table;
chessBoardDiv.appendChild(table);
}
any idea why ?

Categories

Resources