I have a function to add rows in a table using innerHTML:
function addRowToTable(tblParam) {
var tbl =document.getElementById(tblParam);
var lastRow = tbl.rows.length;
var cnt = lastRow; var row = tbl.insertRow(lastRow);
document.form_sample_1.cnt_rltv.value = cnt;
cellLeft.innerHTML = "<td><select class=form-control input-xsmall name=rltv" + cnt + " id=rltv" + cnt + "><option value='' selected=selected> </option><option value='Father'>Father</option>
<option> value='Mother'>Mother</option><option> value='Brother'>Brother</option>
<option>value='Sister'>Sister</option></select></td>"
}
How can I put select option data source from a database?
Instead of inserting a giant string of HTML, create the DOM nodes and hook them up to each other.
var dbResults = ["Mother", "Brother", "Sister"];
var select = document.createElement("select");
for (var i=0; i < dbResults.length; i++) {
var option = document.createElement("option");
option.innerText = dbResults[i];
select.appendChild(option);
}
Then append the select node to whichever parent you want.
var td = document.createElement("td");
td.append(select);
Related
I have added records to a table that contains values in two text boxes and a button per each row. How can I get the record number of a particular button clicked by the user?
<table id="myTable">
</table>
<script>
var table=document.getElementById("myTable");
var i=0;
for(i; i<3; i++)
{
var row = table.insertRow(i);
var cell0=row.insertCell(0);
var element0=document.createElement("input");
element0.type="text";
element0.value = "Hello : " + i;
cell0.appendChild(element0);
var cell1=row.insertCell(1);
var element1=document.createElement("input");
element1.type="text";
element1.value = "Welcome : " + i*2;
cell1.appendChild(element1);
var cell2=row.insertCell(2);
var element2=document.createElement("input");
element2.type="button";
element2.value = "Clcik : " + i*i;
element2.onclick = function show_id() { alert("Record ID"); }
cell2.appendChild(element2);
}
</script>
Why can't you use an index for tracking the record?
Hoping this is the use case you are looking for. Include more details in case you need anything other than this.
<table id="myTable">
</table>
<script>
var table=document.getElementById("myTable");
var i=0;
for(i; i<3; i++)
{
const recordId = i+1;
var row = table.insertRow(i);
var cell0=row.insertCell(0);
var element0=document.createElement("input");
element0.type="text";
element0.value = "Hello : " + i;
cell0.appendChild(element0);
var cell1=row.insertCell(1);
var element1=document.createElement("input");
element1.type="text";
element1.value = "Welcome : " + i*2;
cell1.appendChild(element1);
var cell2=row.insertCell(2);
var element2=document.createElement("input");
element2.type="button";
element2.value = "Clcik : " + i*i;
element2.onclick = function show_id() {
alert("Record ID - " + recordId);
}
cell2.appendChild(element2);
}
</script>
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);
}
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.
How do I get the value of a Bootstrap TouchSpin element inside of a table? I'm currently getting nothing as I don't believe it is finding the element.
Creation of the touchspin and inserting into table
var table = document.getElementById("createOrderTable");
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
row.id = 'row' + rowCount;
// TouchSpin element
var cell1 = row.insertCell(1);
var touchSpinID = 'touchspin' + rowCount;
cell1.innerHTML = "<input id='" + touchSpinID +"' type='text' value='1' name='" + touchSpinID +"'>";
cell1.id = 'cell' + touchSpinID;
//Init TouchSpin
$("input[name='" + touchSpinID +"']").TouchSpin({
verticalbuttons: true,
min: 0,
max: 100000000,
});
Iterating through the table and getting the value of the Touchspin, neither method below works.
var table = document.getElementById("createOrderTable");
var rowCount = table.rows.length;
var productArray = [];
for(i = 1; i < table.rows.length; i++){
var touchspinID = 'touchspin' + i;
var touchspinValue = 0;
cellID = 'cell' + touchspinID;
$(cellID).find(touchspinID).each(function(){
touchspinValue = this.val();
console.log(touchspinValue);
});
$("#createOrderTable tr").each(function () {
$('td', this).each(function () {
var value = $(this).find(touchspinID).val();
console.log(value);
})
})
}
Looking at your code, I believe the issue lies with touchspinID and cellID in that they're both missing the '#' to indicate that you're looking for elements with those specific ids.
Changing these two lines from:
var touchspinID = 'touchspin' + i;
cellID = 'cell' + touchspinID;
to:
var touchspinID = '#touchspin' + i;
cellID = '#cell' + touchspinID;
should fix your issue. Also, you don't need to use .each after the call to .find as the cell will only ever have one "touchspin" element and ids must always be unique:
var touchspinValue = $(cellID).find(touchspinID).val();
console.log(touchspinValue);
If the above doesn't solve your issue, include the table html in your question.
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;
}