adding dynamically the data into the columns of the table in JavaScript - javascript

function add_fields() {
document.getElementById('myTable').innerHTML += '<tr> <td> <textarea name = "Product ID" placeholder = "Product ID" style = "resize: none; width: 100%;" document.getElementById("1")></textarea></td> <td> <textarea name = "Title" placeholder = "Title" style = "resize: none; width: 100%;"></textarea></td><td> <textarea name = "startdate" placeholder = "startdate" style = "resize: none; width: 100%;"></textarea></td> </tr>';
}
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
}
td,
th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
tr:nth-child(even) {
background-color: #dddddd;
}
<div class="set-form">
<input type="button" id="more_fields" onclick="add_fields();" value="Add More" class="btn btn-info" />
</div>
<table id="myTable">
product id : <input type="text" name="fname" id="1"><br>
<thead>
<tr>
<th>Product ID</th>
<th>Title</th>
<th>Start Date</th>
<th>End Date</th>
<th>Excl</th>
<th>Territory</th>
<th>Media</th>
<th>Language</th>
<th>Format</th>
<th>Acquiring Division</th>
<th>Owner</th>
</tr>
</thead>
</table>
I want to add dynamically to the table by selecting the id whenever the user enters the data the data should add automatically to the table.
Is there any better way I want to add a column to the table and data to be added at once but I could not figure out so I planned the above code.
Any suggestions?

Playing a little with your code, I made the following modifications…
HTML stays in HTML, I've added a tr with id="row-type". It's hidden but the content is used to add a new tr when you click Add More. I've modified your existing function accordingly.
CSS stays in CSS, I've moved the table textarea style in the CSS.
As it's not recommended to use .innerHTML +=, I replaced it with .appendChild(…).
I've added a button in the row-type element. So that, when you click Submit, the content of the row is converted from textareas to texts.
As we're only adding in the 3 first tds, I've removed some of the other tds in the HTML to shorten the snippet. But it works exactly the same with all of it (I tried).
I've added a cancel function, in case you finally don't want to add.
…and ended-up with this working snippet:
(See comments in the code for more details)
// TAKIT: Now the content is in the HTML, append it to the current table
function add_fields() {
// TAKIT: Replaced .innerHTML as it's not recommended
var newElement = document.createElement('tr');
newElement.innerHTML = document.getElementById('row-type').innerHTML;
document.getElementById('myTable').appendChild(newElement);
}
// TAKIT: Added this function for when you click on the submit button
function put_in_table(elm) {
var tds = elm.closest('tr').children; // Get all tds of the line you just clicked "submit"
for (var i = 0; i < tds.length; i++) { // For all tds
// replace the HTML with the text value of the textarea (that removes the textareas)
if (tds[i].innerHTML)
tds[i].innerText = tds[i].children[0].value || '';
}
}
// TAKIT: Added this function to cancel the add
function cancel_add(elm) {
elm.closest('tr').outerHTML = ''; // Empty current tr
}
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
}
td,
th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
tr:nth-child(even) {
background-color: #dddddd;
}
/* TAKIT: Added hidden on row type, and moved style of textareas here */
#row-type {
display: none;
}
table textarea {
resize: none;
width: 100%;
}
<div class="set-form"><input type="button" id="more_fields" onclick="add_fields();" value="Add More" class="btn btn-info" /></div>
<table id="myTable">
<!-- TAKIT: Added p element here, it's proper. What is it used for, by the way? -->
<p>product id : <input type="text" name="fname" id="1"></p>
<thead>
<tr>
<th>Product ID</th>
<th>Title</th>
<th>Start Date</th>
<th>End Date</th>
<th>Excl</th>
</tr>
</thead>
<tbody>
<!-- TAKIT: Added body and the "row-type" in it, so that HTML stays in HTML -->
<tr id="row-type">
<td><textarea name="Product ID" placeholder="Product ID"></textarea></td>
<td><textarea name="Title" placeholder="Title"></textarea></td>
<td><input name="startdate" type="date"></td>
<td><input name="enddat" type="date"></td>
<td>
<button onclick="put_in_table(this);">Submit</button> <button onclick="cancel_add(this);">Cancel</button>
</td>
</tr>
</tbody>
</table>
Hope it helps.

I find it easiest to just have a div/span which I write a table in dynamically with javascript, e.g.
example_array = [["Name","Age"],["Antonio","35"]];
function array_to_table(my_array){
my_table_html = '<table>';
for(var i = 0; i<my_array.length; i++){
my_table_html += "<tr>";
for(var j = 0; j < my_array[i].length; j++){
my_table_html += "<td>"+my_array[i][j]+"</td>";
}
my_table_html += "</tr>";
}
my_table_html += '</table>';
document.getElementById("mytable").innerHTML = my_table_html;
}
array_to_table(example_array);
<div id="mytable"></div>
When you have this framework for creating/updating tables, you can edit the array that's fed into the function to dynamically update your table.

Here is a working example, enter the desired values in the first row (I have only the first three elements here). Then click Add, the row will be added to the table.
function add_fields() {
// select the input values
let productId = document.querySelector('#productId').value
let title = document.querySelector('#title').value
let startDate = document.querySelector('#startDate').value
// prepare a new row
let tr = document.createElement('tr')
tr.innerHTML = `
<tr>
<td>
<div id="productId" style="resize: none; width: 100%;">${productId}</div>
</td>
<td>
<div id="title" style="resize: none; width: 100%;">${title}</div>
</td>
<td>
<div id="startDate" style="resize: none; width: 100%;">${startDate}</div>
</td>
</tr>
`
// remove content of textareas
document.querySelector('#productId').value = ''
document.querySelector('#title').value = ''
document.querySelector('#startDate').value = ''
// append a new row to the table
document.querySelector('#myTable').appendChild(tr)
}
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
}
td,
th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
tr:nth-child(even) {
background-color: #dddddd;
}
<div class="set-form">
<input type="button" id="more_fields" onclick="add_fields();" value="Add" class="btn btn-info" />
</div>
</head>
<body>
<table id="myTable">
<thead>
<tr>
<th>Product ID</th>
<th>Title</th>
<th>Start Date</th>
<th>End Date</th>
<th>Excl</th>
<th>Territory</th>
<th>Media</th>
<th>Language</th>
<th>Format</th>
<th>Acquiring Division</th>
<th>Owner</th>
</tr>
<tr>
<td>
<textarea id="productId" placeholder="Product ID" style="resize: none; width: 100%;"></textarea>
</td>
<td>
<textarea id="title" placeholder="Title" style="resize: none; width: 100%;"></textarea></td>
<td>
<textarea id="startDate" placeholder="startdate" style="resize: none; width: 100%;"></textarea> </td>
</tr>
</thead>
</table>
Here are a couple things you might want to know:
I'm using the method querySelector() from document to select an element from the DOM by its class or id. Don't forget to add the # to . before the actual name.
Access the value of an element of type textarea with its property value.
No use of innerHTML += as it will force the browser to re-render all the content of #myTable even if you're just adding a row. Best way is to prepare an element as I do and append it to the table with appendChild().
To easily write HTML inside JavaScript code, you can use backticks `` and insert JS variables directly in the markup with the ${} syntax.

Related

How to show 'no results try again' on a jquery toggle search filter

I am customizing this basic jQuery Data Table with Search Filter tutorial for my own use and it works great except I can't figure out how to toggle to show a specific message when the filter returns no results: https://www.coderbench.com/develop-jquery-data-table-search-filter/
Here is the script:
$(document).ready(function(){
$("#txtsearch").keyup(function(){
var value = $(this).val().toLowerCase();
$("#table tr").filter(function() {
$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
});
});
});
This works for what I need except I want to display the following text above my table when there are no row matches and all rows are toggled hidden:
<span class="warning">Your search returned no results, please modify your entry.</span>
I imagine there's some elaborate conditional statement I could make here but I'm wondering if there's a simple way to do this....as is often the case. Thanks! Here is the full sample page:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("#txtsearch").keyup(function(){
var value = $(this).val().toLowerCase();
$("#table tr").filter(function() {
$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
});
});
});
</script>
<style>
table {
font-family: arial;
border-collapse: collapse;
width: 100%;
}
td, th {
border: 1px solid #e3e3e3;
text-align: left;
padding: 8px;
}
tr:nth-child(even) {
background-color: #efefef;
}
</style>
<div>
<input id="txtsearch" type="text" placeholder="Search Here..." />
<br><br>
<table>
<thead>
<tr>
<th>Movies</th>
<th>Rating</th>
</tr>
</thead>
<tbody id="table">
<tr>
<td>Spiderman Homecoming</td>
<td>9/10</td>
</tr>
<tr>
<td>Wonder Woman</td>
<td>8/10</td>
</tr>
<tr>
<td>The Guardians of Galaxy 2</td>
<td>8/10</td>
</tr>
<tr>
<td>Ant Man</td>
<td>7.5/10</td>
</tr>
</tbody>
</table>
</div>
Here's my try.
I don't use jQuery much so feel free to adapt things to a more "jQuery"-way.
const warning = document.querySelector('.warning');
const table = document.querySelector('table');
$(document).ready(function() {
$("#txtsearch").keyup(function() {
let value = $(this).val().toLowerCase();
let numberOfResults = 0;
$("#table tr").filter((index, tableRow) => {
let isAMatch = $(tableRow).text().toLowerCase().indexOf(value) > -1;
$(tableRow).toggle(isAMatch);
if (isAMatch) {
numberOfResults++;
}
});
if (numberOfResults === 0) {
warning.classList.add('show')
table.classList.add('no-results');
} else {
warning.classList.remove('show');
table.classList.remove('no-results');
}
});
});
table {
font-family: arial;
border-collapse: collapse;
width: 100%;
}
table.no-results {
display: none;
}
td,
th {
border: 1px solid #e3e3e3;
text-align: left;
padding: 8px;
}
tr:nth-child(even) {
background-color: #efefef;
}
.warning {
margin-bottom: 10px;
display: none;
}
.warning.show {
display: block;
}
<div>
<span class="warning">Your search returned no results, please modify your entry.</span>
<input id="txtsearch" type="text" placeholder="Search Here..." />
<br><br>
<table>
<thead>
<tr>
<th>Movies</th>
<th>Rating</th>
</tr>
</thead>
<tbody id="table">
<tr>
<td>Spiderman Homecoming</td>
<td>9/10</td>
</tr>
<tr>
<td>Wonder Woman</td>
<td>8/10</td>
</tr>
<tr>
<td>The Guardians of Galaxy 2</td>
<td>8/10</td>
</tr>
<tr>
<td>Ant Man</td>
<td>7.5/10</td>
</tr>
</tbody>
</table>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>

Delete Dynamic HTML table using table id?

I'm creating multiple tables from one table (table id = table6)
If I created a new table from table id ='table6', I want to delete that newly generated table using its table id. I have assigned table ids to the newly generated tables. what's wrong in my code?
I want to delete this HTML table. Any hint?
var aggTableNum = 0;
function generateAgg() {
const originTable = document.getElementById('table6');
const baseRowTbl = originTable.querySelector('tbody tr');
let newTable = originTable.cloneNode(true);
let newTbody = newTable.querySelector('tbody');
newTable.id = 'newAggTable' + ++aggTableNum;
// for (i = 0; i < 0; i++) {
// newTbody.appendChild(baseRowTbl.cloneNode(true));
// }
newTable.querySelectorAll('input').forEach((element) => {
element.value = '';
});
document.body.appendChild(newTable);
}
function tID() {
$('table').on('click', 'button', function (e) {
alert(e.delegateTarget.id);
var tbl = e.delegateTarget.id;
console.log(tbl);
// if (tbl) tbl.parentNode.removeChild(tbl);
$(tbl).remove();
});
}
table {
border-collapse: collapse;
margin: 1em;
}
thead {
background-color: lightblue;
}
td,
th {
border: solid grey 1px;
padding: 1em;
text-align: center;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button style="margin: 1%" onclick="generateAgg()">Generate New Table</button>
<table id="table6">
<thead>
<th colspan="6">Table</th>
<tr>
<th> Column 1 </th>
<th> Column 2 </th>
</tr>
</thead>
<tbody>
<tr>
<td>
<input>
</input>
</td>
<td><input>
</input></td>
</tr>
<tr>
<td>
<button style="margin: 1%" onclick="tID()">delete </button>
</td>
</tr>
</tbody>
</table>
JsFiddle link - > https://jsfiddle.net/shreekantbatale2/hn0286zd/8/
Though you are getting the table id's value, need to refer that properly with jquery with a leading # in the selector.
Change this:
$(tbl).remove();
...to:
$('#' + tbl).remove();
Then the table removes.

Complete form based on drop down selection

I have a simple form that requires employees to input phone numbers, employee ID, etc. I would like to save them some time (and prevent data entry errors) by allowing them to select their name form a drop down and have the text input fields for phone and ID number autofill based on the name selected.
I have an HTML table that contains all the employee information, but do not know how to pass that information to the proper fields. Code snippet follows:
#emp_data_tbl {
width: 90%
}
#emp_data_tbl td,
#emp_data_tbl th {
border: 1px solid #ddd;
padding: 8px;
}
#emp_data_tbl tr:nth-child(even) {
background-color: #f2f2f2;
}
#emp_data_tbl tr:hover {
background-color: #ddd;
}
#emp_data_tbl th {
padding-top: 12px;
padding-bottom: 12px;
text-align: left;
background-color: #4CAF50;
color: white;
}
<p>Name</p>
<select required>
<option value="" disabled selected hidden>Choose Name...
</option>
<option value="Adam Jackson">Adam Jackson
</option>
<option value="Bill Smith">Bill Smith
</option>
<option value="Chris Clinton">Chris Clinton
</option>
<option value="David Billings">David Billings
</option>
<option value="Eamon Lampsen">Eamon Lampsen
</option>
</select>
<p>Phone</p>
<input type="text" id="phone">
<p>ID</p>
<input type="text" id="IdNum">
<br><br>
<hr><br><br>
<table id="emp_data_tbl">
<caption>In reality, this data table is hidden with CSS display: none but viewable here in this mock up</caption>
<col>
<col>
<col>
<tr>
<th>Name</th>
<th>Phone</th>
<th>ID</th>
</tr>
<tr>
<td>Adam Jackson</td>
<td>111-111-1111</td>
<td>#1111</td>
</tr>
<tr>
<td>Bill Smith</td>
<td>222-222-2222</td>
<td>#2222</td>
</tr>
<tr>
<td>Chris Clinton</td>
<td>333-333-3333</td>
<td>#3333</td>
</tr>
<tr>
<td>David Billings</td>
<td>444-444-4444</td>
<td>#4444</td>
</tr>
<tr>
<td>Eamon Lampsen</td>
<td>555-555-5555</td>
<td>#5555</td>
</tr>
</table>
This will get you started.
#emp_data_tbl {
width: 90%
}
#emp_data_tbl td,
#emp_data_tbl th {
border: 1px solid #ddd;
padding: 8px;
}
#emp_data_tbl tr:nth-child(even) {
background-color: #f2f2f2;
}
#emp_data_tbl tr:hover {
background-color: #ddd;
}
#emp_data_tbl th {
padding-top: 12px;
padding-bottom: 12px;
text-align: left;
background-color: #4CAF50;
color: white;
}
<form action="#">
<label for="name">Name</label><br>
<select id="name" name="name"></select><br><br>
<!--<label for="female">Phone</label><br>
<input type="text" name="phone" id="phone"><br><br>
<label for="id">ID</label><br>
<input type="text" name="id" id="id"><br><br>-->
<input type="submit" value="Submit">
</form>
<br><br>
<hr><br><br>
<table id="emp_data_tbl">
<tr>
<th>Name</th>
<th>Phone</th>
<th>ID</th>
</tr>
<tr>
<td>Adam Jackson</td>
<td>111-111-1111</td>
<td>#1111</td>
</tr>
<tr>
<td>Bill Smith</td>
<td>222-222-2222</td>
<td>#2222</td>
</tr>
<tr>
<td>Chris Clinton</td>
<td>333-333-3333</td>
<td>#3333</td>
</tr>
<tr>
<td>David Billings</td>
<td>444-444-4444</td>
<td>#4444</td>
</tr>
<tr>
<td>Eamon Lampsen</td>
<td>555-555-5555</td>
<td>#5555</td>
</tr>
</table>
<script>
var rows = document.getElementById("emp_data_tbl").rows;
var users = [];
var phonenrs = [];
var ids = [];
//start at i = 1 to skip the header row
for(var i = 1; i < rows.length; i++)
{
users.push(rows[i].cells[0].innerHTML);
phonenrs.push(rows[i].cells[1].innerHTML);
ids.push(rows[i].cells[2].innerHTML);
}
var nameList = document.getElementById("name");
for(var i = 0; i < users.length; i++)
{
nameList.add(new Option(users[i], users[i] + " - " + phonenrs[i] + " - " + ids[i]));
}
</script>
After this, you will need to do something when your user chooses his name.
You can do this by adding an onChange to the selectbox, which holds a function that will be executed the moment the user chooses an option of the selectbox. For example:
<select id="name" name="name" onchange="fillData();"></select>
After this, you can create a Javascript function fillData(), that get's the telephone number and id, belonging to the user and fill in the values with javascript. Something like:
function fillData(){
document.getElementById("phone").value = "";
//get and set your id and phone values here
}

dynamically added dom-elements not responding to jQuery-function

Consider the following code:
$(document).ready(function(){
var table1 = $("table").eq(0);
var row_list;
var rows;
var x;
var y;
$("#mybutton").click(function(){
row_list = table1.find("tr");
rows = row_list.length;
x = $("#field_x").val();
y = $("#field_y").val();
if(x>rows || y>rows){
var num;
if(x>y) num=x;
else num=y;
var n = num-rows;
var row; table1.find("tr").eq(0).clone();
while(1){
row = table1.find("tr").eq(0).clone();
table1.append(row);
n--;
if(n===0) break;
}
n = num-rows;
var td;
while(1){
td = table1.find("td").eq(0).clone();
table1.find("tr").append(td);
n--;
if(n===0) break;
}
}
var text = $("#text").val();
var css = $("#css").val();
$("table:eq(0) tr:eq(" + (x-1) + ") td:eq(" + (y-1) + ")").text(text).css("color", css);
});
table1.find("td").click(function(){
$(this).html("");
});
});
* {
font: 14px normal Arial, sans-serif;
color: #000000;
}
table {
margin: 50px auto;
}
table, td {
border: 1px solid #aaa;
border-collapse: collapse;
}
th {
padding: 10px;
font-weight: bold;
}
td {
background-color: #eeeeee;
width: 80px;
height: 80px;
}
table:first-child tr td {
cursor: pointer;
}
td[colspan="4"]{
text-align:center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tbody>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
<table>
<thead>
<tr>
<th colspan="4">Fill a field:</th>
</tr>
</thead>
<tbody>
<tr>
<td>Text: <br/><input type="text" id="text" value=""></td>
<td>Field X: <br/><input type="text" id="field_x" value=""></td>
<td>Field Y: <br/><input type="text" id="field_y" value=""></td>
<td>CSS: <br/><input type="text" id="css" value=""></td>
</tr>
<tr>
<td colspan="4"><button id="mybutton">Fill</button></td>
</tr>
</tbody>
</table>
What the program does is the following:
The user can choose a field by giving an x-value and a y-value. In this field the content from the input field with label "Text" is displayed.
- This part of the program works fine.
If the user chooses an x-value or a y-value larger than the current number of rows (columns), rows and columns are added until the number of rows/columns is equal to the value in the x-(or y-) field.
- This part of the program also works fine.
The only functionality that does not work is the following:
If the user clicks on one of the non-empty fields in the table, the content of the table is supposed to go back to its natural (empty) state.
To this end, the following function was added to the code (see last couple of lines in the javascript part of the code):
table1.find("td").click(function(){
$(this).html("");
});
This piece of code basically means:
If the user clicks on any box ("td") in the table, the content of this box should disappear.
This is more or less the most simple part of the code. But it's also the one aspect that doesn't work. More precisely: It works for the original boxes, but it doesn't work for any boxes that were added. - And I don't get why it behaved that way.
If you are dynamically adding elements to the DOM and expect to be attaching events to them, you should consider using event delegation via the on() function :
// This will wire up a click event for any current AND future 'td' elements
$(table1).on('click', 'td', function(){
$(this).html("");
});
Simply using click() on it's own will only wire up the necessary event handlers for elements that exist in the DOM at the time of that function being called.
You're assigning the event handlers before the user has a chance to input any data. This means that if an additional row or column is added, the new <td>s need event handlers added manually.
Alternately, you can add a single click handler to the entire table:
table1.click(function (ev) { $(ev.target).html(''); }
The ev.currentTarget property will be the <table> element because that's the element the event handler is registered to, but the ev.target property will be the <td> element that you're looking for.
Here's a JSFiddle to experiment with.
Hey there here's what I thought the answer might be,
HTML File:
<!DOCTYPE html>
<html lang="de-DE">
<head>
<meta charset="UTF-8" />
<style>
* {
font: 14px normal Arial, sans-serif;
color: #000000;
}
table {
margin: 50px auto;
}
table, td {
border: 1px solid #aaa;
border-collapse: collapse;
}
th {
padding: 10px;
font-weight: bold;
}
td {
background-color: #eeeeee;
width: 80px;
height: 80px;
}
table:first-child tr td {
cursor: pointer;
}
td[colspan="4"]{
text-align:center;
}
.pre-height {
min-height: 80px;
}
</style>
</head>
<body>
<table>
<tbody>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td class="pre-height"></td>
<td class="pre-height"></td>
<td class="pre-height"></td>
<td class="pre-height"></td>
</tr>
</tbody>
</table>
<table>
<thead>
<tr>
<th colspan="4">Fill a field:</th>
</tr>
</thead>
<tbody>
<tr>
<td>Text: <br/><input type="text" id="text" value=""></td>
<td>Field X: <br/><input type="text" id="field_x" value=""></td>
<td>Field Y: <br/><input type="text" id="field_y" value=""></td>
<td>CSS: <br/><input type="text" id="css" value=""></td>
</tr>
<tr>
<td colspan="4"><button id="myButton">Fill</button></td>
</tr>
</tbody>
</table>
<script src="jquery.min.js"></script>
<script src="jack.js"></script>
</body>
</html>
JACK.JS file:
window.onload = function() {
'use strict';
/**
* Appends 'n' number of rows to the table body.
*
* #param {Number} n - Number of rows to make.
*/
var makeRows = function(n) {
let tbody= document.getElementsByTagName("table")[0].getElementsByTagName("tbody")[0],
tr = document.querySelector("table:first-of-type tbody tr");
for (let i = 0; i < n; i++) {
let row = Node.prototype.cloneNode.call(tr, true);
tbody.appendChild(row);
}
};
/**
* Appends 'n' number of cells to each row.
*
* #param {Number} n - Number of cells to add to each row.
*/
var makeColumns = function(n) {
let addNCells = (function(n, row) {
for (let i = 0; i < n; i++) {
let cell = Node.prototype.cloneNode.call(td, true);
row.appendChild(cell);
}
}).bind(null, n);
let tbody= document.getElementsByTagName("table")[0].getElementsByTagName("tbody")[0],
td = document.querySelector("table:first-of-type tbody tr td"),
rows = document.querySelectorAll("table:first-of-type tbody tr");
rows.forEach(function(row) {
addNCells(row);
});
};
document.getElementById("myButton").addEventListener("click", () => {
let x = document.getElementById("field_x").value,
y = document.getElementById("field_y").value;
makeColumns(x);
makeRows(y);
});
/**
* Newly added code
*/
(function() {
let table = document.querySelector("table");
// We will add event listener to table.
table.addEventListener("click", (e) => {
e.target.innerHTML = "";
e.target.style.backgroundColor = "orange";
});
})();
};
Edit: And I didn't even answer the question completely. You might wanna attach event listener to the nearest non-dynamic parent so that click event will bubble up and you can capture that, check the code under the comment newly added code.

TableSorter sorting empty input in Td

I'm testing tablesorter and my table is :
Table
It contains list of products and one product has 2 rows, one row contains its name and the other is the input field for the user to make changes.
I would like to do a tablesorter to sort the products with the empty input fields to the top of the table.
Table Expected Result
It means the products which don't have text in the input fields will be displayed on top.
I'm using tablesorter jquery.
my HTML Table: Tr1 holds first 'data' line, TR2 holds the input fields;
<table class="tablesorter">
<thead>
<tr>
<th class="sorter-inputs empty-top code">Code</th>
<th class="sorter-inputs empty-top designation">Designation</th>
</tr>
</thead>
<tbody>
<tr class='tr1'>
<td>
<div class='code'> </div>
</td>
<td>
<div class='designation'>abc 111</div>
</td>
</tr>
<tr class='tr2'>
<td>
<input type="text" class='CodeInput'/>
</td>
<td>
<input type="text" class='designationInput'/>
</td>
</tr>
...
</tbody> </table>
If you are using my fork of tablesorter, you have two options.
1) Leave out the input rows and use the editable widget, which actually makes the table cell editable using contenteditable. This does require a modern browser.
2) Use the input parser & set the emptyTo option to keep empty rows at the top (demo)
NOTE: the parser-input-select.js file used in the demo is actually pointing to the master branch of the repository.
HTML
<table class="tablesorter">
<thead>
<tr>
<th class="sorter-inputs empty-top code">Code</th>
<th class="sorter-inputs empty-top designation">Designation</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<div> </div>
<input type="text" />
</td>
<td>
<div>abc 111</div>
<input type="text" />
</td>
</tr>
...
</tbody>
</table>
* Note *: I don't think using child rows will work in this case because the sort would occur based on the parent row content. So I added a <div> to each cell with the labels.
CSS
html { box-sizing: border-box; }
*, *:before, *:after { box-sizing: inherit; }
.code { width: 20%; }
.designation { width: 80%; }
input { width: 90%; margin: 4px; background: #fc7565; border: solid 1px #999; }
table { border-collapse: collapsed; border-spacing: 0; }
.tablesorter-blue tbody td { padding: 0; vertical-align: bottom; }
td div { background: #ccc; padding: 4px; }
Script
$(function () {
$('table').tablesorter({
theme: 'blue'
});
});

Categories

Resources