I used code to create a <th>, This below code works fine for the first time but doesn't work when i create them repeatedly,i.e, Again and again.
function createTH(){
var noOfRow = document.getElementById("addItemTable").rows.length;
var temp = document.getElementById("addItemTable");
var table = temp.getElementsByTagName('tbody')[0];
var row = table.insertRow(-1);
var cell2 = row.insertCell(0);
var cell3 = row.insertCell(1);
cell2.innerHTML="this is inside table div";
cell2.style="border: dashed;"
cell3.innerHTML="this is inside another another div";
cell3.style="border: dashed;"
var thContent = '<th class="col2">' + '<br>' + 'test' + '   ' + '*' + '' + '</th>'
var mainTable = document.getElementById("addItemTable");
$('#addItemTable>tbody>tr').prepend(thContent);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="m-content" id="elementDiv">
<table id="addItemTable">
<tbody>
</tbody>
</table>
</div>
<input type="button" onclick="createTH()" value="Click to create <th> again and again"/>
My current output is a mess after doing the second click on the button.
My expected output is in following pattern:
<tr>
...
<th><td><td>//I only want to repeat this single line on every click of button.
<th><td><td>
<th><td><td>//I'm looking to create this kind of repetition on click of button.
...
</tr>
For more reference you can visit: Dynamic Creation of th, as this question is continuation of the above mentioned thread. I made a new thread because old thread would become more tedious and the length of question would be increased.
Any help would be greatly appreciated.
The issue is because you're appending thContent to all tr which you select by jQuery, not just the new one. To fix this change the line to only append to the new row instance:
$(row).prepend(thContent);
However it's worth noting that you're using an odd combination of plain JS and jQuery. If you're using jQuery already you can simplify the code drastically:
$('#add').on('click', function() {
var rowHtml = '<tr><th class="col2"><br />test *</th><td>this is inside table div</td><td>this is inside another another div</td></tr>';
$('#addItemTable').append(rowHtml);
});
td { border: dashed; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="m-content" id="elementDiv">
<table id="addItemTable">
<tbody></tbody>
</table>
</div>
<button id="add">Click to create <th> again and again</button>
You keep adding to every row.
Use jQuery consistently and it helps. Also DRY: Do not repeat yourself
Like this
const cellStyle = { "style": "border: dashed;" }
$("#addRow").on("click", function() {
const $tb = $("#addItemTable tbody");
let $newRow = $("<tr/>");
$newRow.append('<th class="col2"><br />test *</th>');
$newRow.append($("<td/>", cellStyle).text("this is inside table cell"));
$newRow.append($("<td/>", cellStyle).text("this is inside another table cell"));
$tb.prepend($newRow);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="m-content" id="elementDiv">
<table id="addItemTable">
<tbody>
</tbody>
</table>
</div>
<input type="button" id="addRow" value="Click to create <tr> again and again" />
You can use row counter to increase index number of row and append data in it when function calls.
Here is Demo
var rowCounter = 0;
function createTH(){
var noOfRow = document.getElementById("addItemTable").rows.length;
var temp = document.getElementById("addItemTable");
var table = temp.getElementsByTagName('tbody')[0];
var row = table.insertRow(-1);
var cell2 = row.insertCell(0);
var cell3 = row.insertCell(1);
cell2.innerHTML="this is inside table div";
cell2.style="border: dashed;"
cell3.innerHTML="this is inside another another div";
cell3.style="border: dashed;"
var thContent = '<th class="col2">' + '<br>' + 'test' + '   ' + '*' + '' + '</th>'
var mainTable = document.getElementById("addItemTable");
$('#addItemTable>tbody>tr').eq(rowCounter).prepend(thContent);
rowCounter++;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="m-content" id="elementDiv">
<table id="addItemTable">
<tbody>
</tbody>
</table>
</div>
<input type="button" onclick="createTH()" value="Click to create <th> again and again"/>
I found one more solution for this question by making use of Outer Html. Just a different approach to this problem.
function createTH() {
var noOfRow = document.getElementById("addItemTable").rows.length;
var temp = document.getElementById("addItemTable");
var table = temp.getElementsByTagName('tbody')[0];
var row = table.insertRow(-1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
elemVal = '<th class="col2">' + "test" + '   ' + '*' + '' + '</th>';
cell1.outerHTML = elemVal;
cell2.innerHTML = "this is inside table div";
cell2.style = "border: dashed;"
cell3.innerHTML = "this is inside another another div";
cell3.style = "border: dashed;"
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="m-content" id="elementDiv">
<table id="addItemTable">
<tbody>
</tbody>
</table>
</div>
<input type="button" onclick="createTH()" value="Click to create <th> again and again" />
Related
This question already has answers here:
Adding an onclick event to a table row
(12 answers)
Closed 4 years ago.
I am adding rows to an existing table using JavaScript insertRow method
For one cell, I want to add an onclick event.
How can I do that using pure JavaScript?
I am attaching my code.
<!DOCTYPE html>
<html>
<head>
<style>
table, td {
border: 1px solid black;
}
</style>
</head>
<body>
<table id="myTable">
<tr>
<td>Row1 cell1</td>
<td>Row1 cell2</td>
</tr>
</table>
<br>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var table = document.getElementById("myTable");
var row = table.insertRow(0);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.innerHTML = "NEW CELL1";
cell2.innerHTML = "NEW CELL2";
cell1.onclick()="xfunc()";
}
function xfunc(){
alert("Hi")
}
</script>
</body>
</html>
onclick is a html property, you have assign a function to this property to handler click event.
In you case:
cell1.onclick = xfunc; // instead of cell1.onclick()="xfunc()";
Update your function as below
<script>
function myFunction() {
var table = document.getElementById("myTable");
var row = table.insertRow(0);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.innerHTML = "NEW CELL1";
cell2.innerHTML = "NEW CELL2";
cell1.onclick=xfunc;
}
function xfunc(){
alert("Hi")
}
</script>
Use the below one.
cell1.addEventListener('click', xfunc);
First you could try something really simple:
cell1.setAttribute('onclick', 'xfunc()');
Maybe this already Handles your problem.
If not you just could use a DIV inside the cell:
var div = document.createElement('div');
div.setAttribute('onclick', 'xfunc()');
div.setAttribute('style', 'height: 100%; width: 100%');
div.innerHTML = 'NEW CELL1';
cell1.appendChild(div);
This should handle the problem for sure.
The only thing im not really sure about is wether a table-cell is capable of onclick attributes :)
LG
I think the problem is that, How you are attaching the event to cell1? Try the following code:
function myFunction() {
var table = document.getElementById("myTable");
var row = table.insertRow(0);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.innerHTML = "NEW CELL1";
cell2.innerHTML = "NEW CELL2";
cell1.onclick = xfunc; //<-- problem was on this line
}
I want to filter out table before loading it to reduce it's size that it would load faster, when its loaded i would like to let user to filter it. I am using public CDN script for filter part, but it does not work on content which is injected to . It only works if whole table is loaded together with page.. what i'am doing wrong?
Jsfilter: <script type="text/javascript" language="javascript" src="https://cdnjs.cloudflare.com/ajax/libs/tablefilter/2.5.0/tablefilter.js"></script>
DetailedRport.html
//this function called on button click it gets user and date to resize data set
<script type="text/javascript">
function myFunction() {
var y = document.getElementById("month-input").value;
var z = document.getElementById("email2").value;
//here is called server side script
google.script.run.withSuccessHandler(onSuccess).functionToRunOnFormSubmit(y, z);
}
//Resized data set gets injected to tbody
function onSuccess(c){
var table=toHTMLTable(c);
document.getElementById('myOutput1').innerHTML = table;
}
//Array to HTML table
function toHTMLTable(a) {
var content = a.map(function(row, i) {
var rowHTML = row.map(function (col) {
return "<td>" + col + "</td>";
}).join("");
return "<tr>" + rowHTML + "</tr>";
}).join("");
return content;
}
</script>
//user selects criteria for data table
<b> Report for:</b>
<select value="" name="email2" id="email2" width="300" autofocus="autofocus" autocorrect="off" autocomplete="off">
<?!= myEmails(); ?>
</select>
<b>Pick Period :</b>
<select name="Student" id="month-input" autofocus="autofocus" autocorrect="off" autocomplete="off">
<?!= myDates(); ?>
</select>
//On click table is loaded based on selection
<input type="button" value="Load Data" class="loadbutton" onclick="myFunction();" >
<br><br>
//Js tablefilter which should work but does not if table is injected
<table id="table1"class="mytable TF" cellspacing="0" cellpadding="0">
<thead>
<tr class="header">
<th style="width:5%;">TASK</th>
<th style="width:20%;">PROJECT</th>
<th style="width:30%;">DATE</th>
<th style="width:10%;">TIME SPENT</th>
<th style="width:10%;">WORDCOUNT</th>
<th style="width:10%;">SPEED</th>
</tr>
</thead>
//Where data table is injected
<tbody id="myOutput1">
</tbody>
</table>
//Setting Js tablefilter source http://tablefilter.free.fr/
<script language="javascript" type="text/javascript">
var tf = setFilterGrid("table1");
</script>
server.gs
// here data set gets filtered based on users selection and is sent back
// Using ArrayLib library
function functionToRunOnFormSubmit(y,z) {
var ss = SpreadsheetApp.openById(id);
var ActiveSheet = ss.getSheetByName("TogglMap");
var StartRow = 2;
var RowRange = ActiveSheet.getLastRow() - StartRow + 1;
var EMWholeRange = ActiveSheet.getRange(StartRow,2,RowRange,13);
var AllValues = EMWholeRange.getDisplayValues();
var dat = y +'-01'
var removeCol = function(arr, colIndex, colIndex2) {
for (var i = 0; i < arr.length; i++) {
var row = arr[i];
row.splice(colIndex, colIndex2);
}
}
removeCol(AllValues, 5 , 6);
var filteredArr1 = ArrayLib.filterByText(AllValues, 1, z)
var filteredArr2 = ArrayLib.filterByText(filteredArr1, 3, dat)
removeCol(filteredArr2, 1 ,1);
Logger.log(AllValues)
return filteredArr2
};
My goal is working JS filter
I have a form like that:
<form>
<table id="table">
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>SVNr</th>
</tr>
<tr>
<td contenteditable="true">Jill</td>
<td contenteditable="true">Smith</td>
<td class="svnr" contenteditable="true">50</td>
<td><input type="submit" value="Remove" onclick="DeleteRow(this)"></td>
</tr>
<tr>
<td contenteditable="true">Eve</td>
<td contenteditable="true">Jackson</td>
<td class="svnr" contenteditable="true">94</td>
<td><input type="submit" value="Remove" onclick="DeleteRow(this)"></td>
</tr>
</table>
<input type="button" value="Save Changes">
</form>
This one works perfectly. Futhermore, I want to add table rows to my table programmatically.
I do it this way:
count = numberOfRows;
formular[count] = new Object();
formular[count]["Firstname"] = document.getElementById("Firstname").value;
formular[count]["Lastname"] = document.getElementById("Lastname").value;
formular[count]["SVNr"] = document.getElementById("SVNr").value;
var table = document.getElementById("table");
var TR = table.insertRow(count);
var TD = document.createElement("td");
TD.setAttribute("contenteditable", "true");
var TD2 = document.createElement("td");
TD2.setAttribute("contenteditable", "true");
var TD3 = document.createElement("td");
TD3.setAttribute("contenteditable", "true");
TD3.className = "svnr";
var TD4 = document.createElement("td");
var TXT = document.createTextNode(formular[count]["Firstname"]);
var TXT2 = document.createTextNode(formular[count]["Lastname"]);
var TXT3 = document.createTextNode(formular[count]["SVNr"]);
var Input = document.createElement("input");
Input.type = "submit";
Input.value = "Remove";
Input.onclick = "DeleteRow(this);";
TD.appendChild(TXT);
TR.appendChild(TD);
TD2.appendChild(TXT2);
TR.appendChild(TD2);
TD3.appendChild(TXT3);
TR.appendChild(TD3);
TD4.appendChild(Input);
TR.appendChild(TD4);
document.getElementById("Firstname").value = "";
document.getElementById("Lastname").value = "";
document.getElementById("SVNr").value = "";
Also this code is working well. The only problem is that the Remove function doesn't work correctly for the table rows I added programmatically.
My Removing function looks like that:
function DeleteRow(o) {
var p = o.parentNode.parentNode;
p.parentNode.removeChild(p);
}
This function removes ALL programmatically added values if I press the button for one of them. This function works for the 2 entries in the form I didn't add programmatically but as I said, if I press the Remove button for one of added entries, it removes all programmatically added rows and not just the chosen one.
You need to add in something to uniquely identify each tr. You could set a custom attribute on each tr, set a unique id, etc. and pass the unique value to the delete function.
In addition you may find it easier to work with tables by using the DOMTable properties & methods:
http://www.javascriptkit.com/domref/tableproperties.shtml
http://www.javascriptkit.com/domref/tablemethods.shtml
I am creating a program that connects to Firebase Realtime Database and displays the value in a table.
Her is my code:
var leadsRef = database.ref('leads/'+leadID);
var table = document.getElementById('remarksTable');
leadsRef.on('child_added', function(snapshot) {
var remark = snapshot.val().remark;
var timestamp = snapshot.val().timestamp;
var row = document.createElement('tr');
var rowData1 = document.createElement('td');
var rowData2 = document.createElement('td');
var rowData3 = document.createElement('td');
var rowDataText1 = document.createTextNode(remark);
var rowDataText2 = document.createTextNode(timestamp);
var rowDataText3 = document.createTextNode("Some text");
rowData1.appendChild(rowDataText1);
rowData2.appendChild(rowDataText2);
rowData3.appendChild(rowDataText3);
row.appendChild(rowData1);
row.appendChild(rowData2);
row.appendChild(rowData3);
table.appendChild(row);
});
leadID is an ID which I get from the current url, it contains the correct value so no issues there, path is also absolutely right.
Here is the table code:
<table class="table table-bordered" id="remarksTable">
<tr>
<th><strong>Created On</strong></th>
<th><strong>Timestamp 2</strong></th>
<th><strong>Remarks</strong></th>
</tr>
<tr>
<td>12312313231</td>
<td>12312312312</td>
<td>just a remark.</td>
</tr>
</table>
Now, when I run the page, it connects to the Firebase database and loads the required values, creates table row and table data, attaches text to it and then finally attaches the row to table with the id of remarksTable but it is not creating rows properly. Please note the table is creating using Bootstrap.
This is how it looks:
As you can see, the first row displays fine but the next 2 rows which were created by javascript looks a bit different.
The most likely reason is that you are appending the new row to the table element and not the tbody element inside it, which is interacting poorly with the stylesheet that you didn't include in the question.
Note that all tables have a tbody element. The start and end tags for it are optional so it will be inserted by HTML parsing rules if you don't provide one (or more) explicitly).
#Quentin is right, or you can simply add new rows this way:
var table = document.getElementById("remarksTable");
var row = table.insertRow();
var rowData1 = row.insertCell(0);
var rowData2 = row.insertCell(1);
var rowData2 = row.insertCell(2);
rowData1.innerHTML = remark;
rowData2.innerHTML = timestamp;
rowData3.innerHTML = "some text";
Here is a working demo
function addCells() {
var table = document.getElementById("remarksTable");
var row = table.insertRow();
var rowData1 = row.insertCell(0);
var rowData2 = row.insertCell(1);
var rowData3 = row.insertCell(2);
rowData1.innerHTML = "your remark";
rowData2.innerHTML = "your timestamp timestamp";
rowData3.innerHTML = "some text";
}
<table id="remarksTable" border=1>
<tr>
<td>first cell</td>
<td>2nd cell</td>
<td>3rd cell</td>
</tr>
</table>
<button onclick="addCells()">Add New</button>
i Want to add loop to read all html table rows data which are "Input text" and want to show all the "Input text" data according to row as alert by click once on submit this code is only working for one table row data which
is generated
function myFunction() {
var table = document.getElementById("myTable");
var row = table.insertRow(0);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
var textf1 = '<input type="text" value="Fname1" id="text1" />';
var textf2 = '<input type="text" value="Fname2" id="text2" /> ';
cell1.innerHTML = textf1;
cell2.innerHTML = textf2;
cell3.innerHTML = textf4;
}
function first(){
}
alert("Hello"+text1.value+"Your Surname Is "+text2.value+" You Have Chosen");
return myFunction()
}
<
<p>Click the button to add a new row at the first position of the table and then add cells and content.</p>
<table id="myTable"></table>
<table id="myTable1"></table>
<br>
<div id="first"></div>
<button onclick="myFunction()">Add Your First row</button>
<button onclick="Submit()">Submit</button>
No so much a solution, but this might get you going.
To create a new row...
HTML
<input type="button" id="mybutton">Add Row</button>
jQuery
$('#mybutton').click(function(){
$('#mytable tr:last').after('<tr><td>...</td></tr>');
});
To "loop" through your table...
jQuery
// Each row in your table.
$('#mytable> tbody > tr').each(function (key, row) {
var $row = $(row);
var $input = $row.find(':input');
// Each input for the given row.
$.each($input, function (key, element) {
var $element = $(element);
console.log($element);
});
});