I have a button as well as in a table row.When I click on button new row should be added in the table and button should be present in newly added row .refer the picture
Here's a quick solution to adding new rows with buttons that will also add new rows.
You didn't add any code, but this works.
https://jsfiddle.net/scheda/Lhsvmqoy/
var b = document.querySelector('.clicky')
var table = document.querySelector('table');
var insert_this = '<tr><td><input type="text" placeholder="Look ma!"/><button class="clicky">Add more stuff</button></td></tr>';
document.querySelector('body').addEventListener('click', function(e) {
if (e.target.className === 'clicky') {
table.innerHTML += insert_this;
}
});
This should work as you expect:
<!DOCTYPE html>
<head>
<style>
td,table{border:solid 1px;}
</style>
<title>Table sample </title>
</head>
<body>
<table id="myTable">
<tr>
<td>Row 1</td><td></td>
</tr>
<tr>
<td>Row 2</td><td><button id="newRow">New Row (original button)</button></td>
</tr>
</table>
</body>
<script>
function addRow() {
// Get a reference to the table
var tableRef = document.getElementById('myTable');
// Insert a row in the table at the end
var newRow = tableRef.insertRow(tableRef.rows.length);
// Insert a cell in the row at index 0
var newCell = newRow.insertCell(0);
newCell.innerHTML="Row " + tableRef.rows.length;
var newCell = newRow.insertCell(1);
// Append button node to the cell
var newButton = document.getElementById('newRow');
newCell.appendChild(newButton);
}
function addEvent(elem, event, fn) {
if (elem.addEventListener) {
elem.addEventListener(event, fn, false);
}else {
elem.attachEvent("on" + event, function() {
// set the this pointer same as addEventListener when fn is called
return(fn.call(elem, window.event));
});
}
}
var mybutton = document.getElementById("newRow");
addEvent(mybutton,"click",addRow);
</script>
</html>
Source/Credits:
The addEventListener function: adding event listener cross browser
Add row function (modified from):
https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableElement/insertRow
Related
Basically, I am comparing the data in two sheets, so I want to show a dialog box with the data of two cells from two sheets and two buttons for the user to select which data cell is correct. Then I would like to loop through all the data that differed from one sheet to the other.
How can I show a dialog with the data, make the script wait for the button to be pressed and then go to the next item on the list?
This is the script that I have so far:
<script>
function myfunction() {
google.script.run.withSuccessHandler(qcComparison).qcGetData();
}
function qcComparison(sheetsData) {
var sheet1 = sheetsData["sheet1"];
var sheet2 = sheetsData["sheet2"];
var lastRow = sheet1.length;
var lastCol = sheet1[0].length
var headers = sheet1[0];
for (var row=1; row<=lastRow; row++) {
for (var col=0; col<lastCol; col++) {
// Do the comparison one cell at a time
var value1 = sheet1[row][col];
var value2 = sheet1[row][col];
if (value1 != value2) {
// Do something
}
}
}
}
document.addEventListener("DOMContentLoaded", myfunction());
</script>
And this is the HTML dialog that I wan to update with the data:
<table id="qc-table" class="qc-table">
<tr>
<td><button id="sheet-1" class="btn btn-primary btn-sm">Sheet 1</button></td>
<td class="profile-data"><p id="sheet-1-profile">Data from cell 1</p></td>
</tr>
<tr>
<td><button id="sheet-2" class="btn btn-secondary btn-sm">Sheet 2</button></td>
<td class="profile-data"><p id="sheet-2-profile">Data form cell 2</p></td>
</tr>
</table>
To display a dialog box when the values are not equal you can call an HTML service to create the HTML within Apps Script and then use getUi().showModalDialog.
EDIT: for loops aren't the best solution since they will continue to execute while the dialog box is open. It is better to use recursion in this case.
Sample code below:
var sheet1 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1");
var sheet2 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet2");
var range1 = sheet1.getRange(1,1,sheet1.getLastRow(),sheet1.getLastColumn()).getValues();
var range2 = sheet2.getRange(1,1,sheet2.getLastRow(),sheet2.getLastColumn()).getValues();
function qcComparison() {
var row = 0, col = 0;
compare(row, col);
}
function compare(row, col) {
Logger.log(row, col);
if (range1[row][col] != range2[row][col]) {
Logger.log("Different values!");
var html = HtmlService.createTemplateFromFile("page");
html.row = row;
html.col = col;
html.cell1 = range1[row][col];
html.cell2 = range2[row][col];
var htmlOutput = html.evaluate();
SpreadsheetApp.getUi().showModalDialog(htmlOutput, 'Choice');
}
else {
compareNext(row, col);
}
}
function compareNext(row, col) {
Logger.log("Compare next", row, col);
if (col < range1[row].length) {
if (row < range1[col].length-1) {
compare(++row, col);
}
else {
row = 0;
compare(row, ++col);
}
}
return;
}
The HTML is changed to accept values from Apps Script, sample code below:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<table id="qc-table" class="qc-table">
<tr>
<td>
<button id="sheet-1" class="btn btn-primary btn-sm" onclick="google.script.run.setSheet1(<?=row?>,<?=col?>,<?=cell1?>);google.script.host.close();">Sheet 1</button></td>
<td class="profile-data"><p id="sheet-1-profile">Data from Sheet 1: <?=cell1?> </p></td>
</tr>
<tr>
<td><button id="sheet-2" class="btn btn-secondary btn-sm" onclick="google.script.run.setSheet2(<?=row?>,<?=col?>,<?=cell2?>);google.script.host.close();">Sheet 2</button></td>
<td class="profile-data"><p id="sheet-2-profile">Data from Sheet 2: <?=cell2?> </p></td>
</tr>
</table>
</body>
</html>
Note that the script now runs functions upon click of Sheet 1 or Sheet 2 to update the values:
function setSheet1(row, col, value) {
sheet2.getRange(++row,++col).setValue(value);
compareNext(--row, --col);
}
function setSheet2(row, col, value) {
sheet1.getRange(++row,++col).setValue(value);
compareNext(--row, --col);
}
References:
showModalDialog()
Templated HTML
Communication between HTML and Apps Script
I'm developing a web application.My App is using Javascript, PHP, HTML. I already done apply code to upload xlsx , attach it on screen .
Here's my Code
<script type="text/javascript" src="simple-excel.js"></script>
<table width=50% align="left" border=0 STYLE="border-collapse:collapse;">
<tr>
<td style="width:9.2%"><b>Load CSV file</b></td>
<td style="width:1%"><b>:</b></td>
<td style="width:15%"><input type="file" id="fileInputCSV" /></td>
</tr>
</table>
<table id="result"></table>
<script type="text/javascript">
// check browser support
// console.log(SimpleExcel.isSupportedBrowser);
var fileInputCSV = document.getElementById('fileInputCSV');
// when local file loaded
fileInputCSV.addEventListener('change', function (e) {
// parse as CSV
var file = e.target.files[0];
var csvParser = new SimpleExcel.Parser.CSV();
csvParser.setDelimiter(',');
csvParser.loadFile(file, function () {
// draw HTML table based on sheet data
var sheet = csvParser.getSheet();
var table = document.getElementById('result');
table.innerHTML = "";
sheet.forEach(function (el, i) {
var row = document.createElement('tr');
el.forEach(function (el, i) {
var cell = document.createElement('td');
cell.innerHTML = el.value;
row.appendChild(cell);
});
table.appendChild(row);
});
});
});
</script>
Here's my UI
How do i supposed to do for hide/erase the null cell(Red Mark)?
It seems your CSV has an empty line at the bottom. Even if it is empty, as far as "sheet" is concerned, it will have one field as long as a carriage return is there.
I'd check to see if the content of the "el" contains anything before executing your el.forEach()
Put some condition inside el.forEach
Like this
el.forEach(function (el, i) {
if(el.value!="")
{
var cell = document.createElement('td');
cell.innerHTML = el.value;
row.appendChild(cell);
}
});
I'm trying to run through a table and change each cell based on the row. Table example:
<table id='myTable'>
<tr>
<td><div id='A1'></div></td>
<td><div id='A2'></div></td>
</tr>
<tr>
<td><div id='A1'></div></td>
<td><div id='A2'></div></td>
</tr>
</table>
Function example (in script under body):
function myFunction(){
var table = $('#myTable');
var rows = table.find('tr');
rows.each(function(i, r){
var cells = r.find('td');
if(i==1){//to edit second row, for example
cells.each(function(j,c){
var square = c.getChild();//attempt to get the div in the td
square.innerHTML='html here';
});
}
});
}
$(document).load(myFunction);
The example shown is non-specific version of the actual function I'm trying to run.
To be clear, I have linked to the jQuery 2.1 CDN, so the page should be able to read jQuery.
Console shows no errors, but still does not run appear to run the function. Checking the tested row in the console shows no change to the html in the div. Any advice for this?
When I run it I get an error on r.find() because .find() is a jQuery function and needs to be called on a jQuery object, which r is not. Simply wrapping it in a $() works.
function myFunction(){
var table = $('#myTable');
var rows = table.find('tr');
rows.each(function(i, r){
var cells = $(r).find('td');
if(i==1){//to edit second row, for example
cells.each(function(j,c){
var square = c.getChild();//attempt to get the div in the td
square.innerHTML='html here';
});
}
});
}
https://jsfiddle.net/k50o8eha/1/
You may need to do asomething similar to the c.getChild();
Here's a simplified version :
$("#myTable tr").each(function(i, r){
if(i==1)
{
$(this).find('td').each(function()
{
$(this).find("div").html("html here");
});
}
});
Example : https://jsfiddle.net/DinoMyte/4dyph8jh/11/
Can you give this a try...
$( document ).ready(function() {
var table = $('#myTable');
var rows = table.find('tr');
rows.each(function(i, r){
var cells = r.find('td');
if(i==1){//to edit second row, for example
cells.each(function(j,c){
var square = c.getChild();//attempt to get the div in the td
square.innerHTML='html here';
});
}
});
});
or shorthand...
$(function() {
});
$( document ).ready(function() {
var table = $('#myTable');
var rows = table.find('tr');
rows.each(function(i, r){
var cells = $(r).find('td');
if(i==1){//to edit second row, for example
cells.each(function(j,c){
var square = $(c).children('div');
square.text('html here');
});
}
});
});
table{
background-color: #eee;
width: 300px;
height: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id='myTable'>
<tr>
<td><div id='A1'></div></td>
<td><div id='A2'></div></td>
</tr>
<tr>
<td><div id='A1'></div></td>
<td><div id='A2'></div></td>
</tr>
</table>
This works, you can try this
JSBIN
function myFunction(){
var table = $('#myTable');
var rows = table.find('tr');
rows.each(function(i){
if(i==1){//to edit second row, for example
$(this).find('td').each(function(j){
$(this).find('div').html('html here');
});
}
});
}
$(document).ready(myFunction);
first the "id" should be unique to an element... but ok, this should do the trick:
$(document).ready(function(){
$("#myTable>tr:odd").children("div").text('html here');
});
If you want to put html code in the div, change text for html. if you want to specify the row then:
$(document).ready(function(){
myRow = //set its value...
$("#myTable>tr").each(function(idx, element){
if(idx == myRow){
element.children("div").text('html here');
}
}, myRow);
});
I am new to javascript.
Can anyone help me to implement an onclick event on click of a HTML table row created through javascript?
Kindly note that I am inserting the data in table cells using innerHTML.
Below is the code snippet of what i have tried.?
Java Script function:
function addRow(msg)
{
var table = document.getElementById("NotesFinancialSummary");
var finSumArr1 = msg.split("^");
var length = finSumArr1.length-1;
alert("length"+ length);
for(var i=1; i<finSumArr1.length; i++)
{
var row = table.insertRow(-1);
var rowValues1 = finSumArr1[i].split("|");
for(var k=0;k<=10;k++)
{
var cell1 = row.insertCell(k);
var element1 = rowValues1[k];
cell1.innerHTML = element1;
}
}
for(var i=1; i<rowCount; i++)
{
for(var k=0;k<=10;k++)
{
document.getElementById("NotesFinancialSummary").rows[i].cells[k].addEventListener("click", function(){enableProfileDiv()}, false);
}
}
}
HTML table code in jsp :
<TABLE id="NotesFinancialSummary" width="800px" border="1" align="left" >
<tr >
<th>Symbol</th>
<th>Claimant</th>
<th>MJC</th>
<th>S</th>
<th>Type</th>
<th>Indemnity Resv</th>
<th>Indemnity Paid</th>
<th>Medical Resv</th>
<th>Medical Paid</th>
<th>Legal Resv</th>
<th>Legal Paid</th>
</tr>
<tr>
<td>
</td>
<TD> </TD>
<TD> </TD>
<TD> </TD>
<TD> </TD>
<TD> </TD>
<TD> </TD>
<TD> </TD>
<TD> </TD>
<TD> </TD>
<TD> </TD>
</tr>
</table>
<table id="table"></table>
$("#table").append("<tr><td>Hi there</td></tr>");
$("#table").on( "click", "tr", function(){
// do something
alert( $(this).children("td:first").text() );
});
Any time the click event bubbles up to <table id="table">, this function will be called (no matter if the <tr>s are inserted dynamically, or hard coded).
This will require the jQuery library
http://jquery.com/
http://api.jquery.com/on/
One way to do it would be using document.createElement
Instead of doing:
yourParentElement.innerHTML = "<tr>Something</tr>";
You can do
var tr = document.createElement("tr");
tr.innerHTML = "Something";
tr.onclick = function() {
//code to be executed onclick
};
yourParentElement.appendChild(tr);
Another way, would be to use an id (only if you're doing this once, you don't want duplicated ids):
yourParentElement.innerHTML = "<tr id='someId'>Something</tr>";
document.getElementById("someId").onclick = function() { //fetch the element and set the event
}
You can read more about events here, but just so you have an idea onclick will only let you set one function.
If you want a better solution you can use something like addEventListener, but it's not crossbrowser so you may want to read up on it.
Lastly, if you want to set up an event on every tr you can use:
var trs = document.getElementByTagName("tr"); //this returns an array of trs
//loop through the tr array and set the event
after you insert your <tr> using innerHTML, create a click event listener for it.
document.getElementById("the new id of your tr").addEventListener("click", function() {
what you want to do on click;
});
Something like this: http://jsfiddle.net/gnBtr/
var startEl = document.getElementById('start');
var containerEl = document.getElementById('container');
var inner = '<div id="content" style = "background: pink; padding:20px;" > click on me </div>'
// Function to change the content of containerEl
function modifyContents() {
containerEl.innerHTML = inner;
var contentEl = document.getElementById('content');
contentEl.addEventListener("click", handleClickOnContents, false);
}
// listenting to clikc on element created via innerHTML
function handleClickOnContents() {
alert("you clicked on a div that was dynamically created");
}
// add event listeners
startEl.addEventListener("click", modifyContents, false);
Check it out:
$('#your_table_id tbody').on('click', 'tr', function (e) {
$('td', this).css('background-color', 'yellow');
} );
css:
tr:hover td{
background-color: lightsteelblue !important;
}
It works fine for me, specially when I'm using jquery dataTable pagination.
I'm delevoling an app with phonegap for android and I'm trying to make a FOR loop in javascript with html table rows. I tried using the document.write but all of the content in the page desapears, show just what it's in the document.write.
The code I have is this one:
<table id="hor-minimalist-b">
<script language=javascript>
for (var i=0; i<3; i++) {
document.write('<tr>');
document.write('<td>');
document.write('<input type="text" name="valor" id="valor" value="key' + i'">');
document.write('</td>');
document.write('</tr>');
}
</script>
</table>
Thanks.
It's because you are just putting text in the page, you need to "create" the element and append them to the table.
You can do it this way:
<table id="hor-minimalist-b"><thead></thead><tbody></tbody></table>
<script language="javascript">
var table = document.getElementById('hor-minimalist-b'); // get the table element
var tableBody = table.childNodes[1]; // get the table body
var tableHead = table.childNodes[0]; // get the table head
for (var i=0; i<3; i++) {
var row = document.createElement('tr'); // create a new row
var cell = document.createElement('td'); // create a new cell
var input = document.createElement('input'); // create a new input
// Set input properties
input.type = "text";
input.id = "valor"; // It's not a good idea (to have elements with the same id..)
input.name = "valor";
input.value = "key" + i;
cell.appendChild(input); // append input to the new cell
row.appendChild(cell); // append the new cell to the new row
tableBody.appendChild(row); // append the row to table body
}
</script>
insertRow() and insertCell() will probably work too, but I did not test it yet