Javascript creating an onclick event for a dynamic table row - javascript

I'm having trouble attaching an onclick event to my dynamic table rows.
What I have is here:
function parseOrderLine(data) {
var obj = JSON.parse(data);
if (obj.length > 0) {
var tbl = document.createElement('table');
var row = tbl.insertRow(0);
var cell = row.insertCell(0);
cell.innerHTML = "Code";
cell = row.insertCell(1);
cell.innerHTML = "Size";
cell = row.insertCell(2);
cell.innerHTML = "Description";
cell = row.insertCell(3);
cell.innerHTML = "Type";
cell = row.insertCell(4);
cell.innerHTML = "Price";
cell.style.textAlign = "right";
for (var i = 0; i < obj.length; i++) {
row = tbl.insertRow(i + 1);
row.className = "results_row";
cell = row.insertCell(0);
cell.innerHTML = obj[i].Code;
cell = row.insertCell(1);
cell.innerHTML = obj[i].Size;
cell = row.insertCell(2);
cell.innerHTML = obj[i].Description;
cell = row.insertCell(3);
cell.innerHTML = obj[i].Type;
cell = row.insertCell(4);
cell.innerHTML = parseFloat(obj[i].Price).toFixed(2);
cell.style.textAlign = "right";
//row.addEventListener("click", function(){ alert('listen'); });
row.onclick = (function(){ alert('click'); });
}
return tbl.outerHTML;
}
else { ...
As you can see I have tried both setting the onclick event and adding a listener. Neither seem to work.
I'm hoping someone can tell me I'm just being crazy and have overlooked something obvious. ;0)
Any help appreciated guys.
Thanks for reading.
Jas

Your problem is on the tbl.outerHTML.
When you add an event listener using addEventListener, Javascript does not add the method to your HTML code in the onclick attribute, it is added only to the DOM. So when you use tbl.outerHTML you listener isn't added to the returned HTML code. The same is applicable for the row.onclick = function()...
If you want to keep the event listener when using outerHTML I suggest you go with setAttribute:
function createTable()
{
var obj = [1,2,3,4,5];
var tbl = document.createElement('table');
var row = tbl.insertRow(0);
var cell = row.insertCell(0);
cell.innerHTML = "Code";
cell = row.insertCell(1);
cell.innerHTML = "Size";
cell = row.insertCell(2);
cell.innerHTML = "Description";
cell = row.insertCell(3);
cell.innerHTML = "Type";
cell = row.insertCell(4);
cell.innerHTML = "Price";
cell.style.textAlign = "right";
for (var i = 0; i < obj.length; i++) {
row = tbl.insertRow(i + 1);
row.className = "results_row";
cell = row.insertCell(0);
cell.innerHTML = obj[i].Code;
cell = row.insertCell(1);
cell.innerHTML = obj[i].Size;
cell = row.insertCell(2);
cell.innerHTML = obj[i].Description;
cell = row.insertCell(3);
cell.innerHTML = obj[i].Type;
cell = row.insertCell(4);
cell.innerHTML = parseFloat(obj[i].Price).toFixed(2);
cell.style.textAlign = "right";
//row.addEventListener("click", function(){ alert('listen'); });
row.setAttribute('onclick', "(function(){ alert('click'); })()");
}
return tbl.outerHTML;
}
document.getElementById('test').innerHTML = createTable();
<div id="test"></div>
HOWEVER it's not the best solution, you should not use outerHTML when you want in fact use the object you just created (in your case, the table). You should add it in the DOM using the appendChild method, doing this way you can use addEventListener:
function createTable()
{
var obj = [1,2,3,4,5];
var tbl = document.createElement('table');
var row = tbl.insertRow(0);
var cell = row.insertCell(0);
cell.innerHTML = "Code";
cell = row.insertCell(1);
cell.innerHTML = "Size";
cell = row.insertCell(2);
cell.innerHTML = "Description";
cell = row.insertCell(3);
cell.innerHTML = "Type";
cell = row.insertCell(4);
cell.innerHTML = "Price";
cell.style.textAlign = "right";
for (var i = 0; i < obj.length; i++) {
row = tbl.insertRow(i + 1);
row.className = "results_row";
cell = row.insertCell(0);
cell.innerHTML = obj[i].Code;
cell = row.insertCell(1);
cell.innerHTML = obj[i].Size;
cell = row.insertCell(2);
cell.innerHTML = obj[i].Description;
cell = row.insertCell(3);
cell.innerHTML = obj[i].Type;
cell = row.insertCell(4);
cell.innerHTML = parseFloat(obj[i].Price).toFixed(2);
cell.style.textAlign = "right";
row.addEventListener("click", (function(){ alert('click'); }));
}
return tbl;
}
document.getElementById('test').appendChild(createTable());
<div id="test"></div>

Related

Html table creation probleme

i wanted to create an html table using this function to generate a table . in order to test it if it gives any result i made a smaller test using numbers ( instead of my own data ) but it doest work.
here is my code :
function showFinalTable()
{
let finalTableHeading = document.createElement("h3");
finalTableHeading.innerHTML = "Table finale";
let table = document.createElement("table");
table.classList.add("final-table");
let thead = table.createTHead();
let row = thead.insertRow(0);
let headings = [
"Process",
"Arrival Time",
"Total Burst Time",
"Completion Time",
"Turn Around Time",
"Waiting Time",
"Response Time",
];
headings.forEach((element, index) => {
let cell = row.insertCell(index);
cell.innerHTML = element;
});
let tbody = table.createTBody();
for (let i = 0; i < 5; i++) {
let row = tbody.insertRow(i);
let cell = row.insertCell(0);
cell.innerHTML = "P" + (i + 1);
cell = row.insertCell(1);
cell.innerHTML = 5;
cell = row.insertCell(2);
cell.innerHTML = 7;
cell = row.insertCell(3);
cell.innerHTML = 8;
cell = row.insertCell(4);
cell.innerHTML = 15;
cell = row.insertCell(5);
cell.innerHTML = 13;
cell = row.insertCell(6);
cell.innerHTML = 17;
}
}
You need to also appendChild the elements you create with createElement.
Adding this line at the end makes it work: document.body.appendChild(table);
Full snippet, click "Run" to see output:
function showFinalTable() {
let finalTableHeading = document.createElement("h3");
finalTableHeading.innerHTML = "Table finale";
document.body.appendChild(finalTableHeading);
let table = document.createElement("table");
table.classList.add("final-table");
let thead = table.createTHead();
let row = thead.insertRow(0);
let headings = [
"Process",
"Arrival Time",
"Total Burst Time",
"Completion Time",
"Turn Around Time",
"Waiting Time",
"Response Time",
];
headings.forEach((element, index) => {
let cell = row.insertCell(index);
cell.innerHTML = element;
});
let tbody = table.createTBody();
for (let i = 0; i < 5; i++) {
let row = tbody.insertRow(i);
let cell = row.insertCell(0);
cell.innerHTML = "P" + (i + 1);
cell = row.insertCell(1);
cell.innerHTML = 5;
cell = row.insertCell(2);
cell.innerHTML = 7;
cell = row.insertCell(3);
cell.innerHTML = 8;
cell = row.insertCell(4);
cell.innerHTML = 15;
cell = row.insertCell(5);
cell.innerHTML = 13;
cell = row.insertCell(6);
cell.innerHTML = 17;
}
document.body.appendChild(table);
}
showFinalTable()

New row disappearing after getting added to html

I am using the following code to add a new row dynamically to my HTML.
When I enter the details and hit submit, the new row shows up momentarily and disappears.
What am I doing wrong?
function addNewRow(){
var tab = document.getElementById("table"),
newRow = tab.insertRow(table.length),
cell1 = newRow.insertCell(0),
cell2 = newRow.insertCell(1),
cell3 = newRow.insertCell(2),
cell4 = newRow.insertCell(3),
cell5 = newRow.insertCell(4),
date = document.getElementById("date-input").value,
time = document.getElementById("time-input").value,
amount = document.getElementById("amount-input").value,
source = document.getElementById("source-input").value,
destination = document.getElementById("dest-input").value;
cell1.innerHTML = date;
cell2.innerHTML = time;
cell3.innerHTML = amount;
cell4.innerHTML = source;
cell5.innerHTML = destination;
}
var btn = document.getElementById("button");
btn.addEventListener('click', function(){
addNewRow();
})

Javascript - Id value Increment rows Does Not Work and Remove Rows By Id

I already created the add rows but my problem is, the value of the id that I created doesn't increment. I just stick to 1 result.
I also want to include remove rows so whenever I click the button "remove" the row with specific id will remove.
Here's my jsfiddle
<script>
var rowID;
function myFunction() {
rowID++;
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);
rowID=1;
cell1.innerHTML = "###";
cell2.innerHTML = "###";
cell3.innerHTML = rowID;
cell4.innerHTML = "<button id=''>Remove</button>";
}
Thanks in advance
This is because you set it back here
var cell4 = row.insertCell(3);
rowID=1; //<-- NOT NEED
cell1.innerHTML = "###";
remove this row.
Here is the jsFiddle. And init it with var rowID = 0;
You need to set your variable to 0 when defining it in order to add 1 to it with the ++ operator. Also remove the rowID = 1 (it resets it to 1) in your code as following:
<script>
var rowID = 0;
function myFunction() {
rowID++;
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);
cell1.innerHTML = "###";
cell2.innerHTML = "###";
cell3.innerHTML = rowID;
cell4.innerHTML = "<button id=''>Remove</button>";
}
I think you had a couple of typos, see in the comments:
//rowId must be initialized to a number or you'll get Nan with rowId++
var rowID = 0;
function myFunction() {
rowID++;
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);
//this is the reason of your bug
//rowID=1;
cell1.innerHTML = "###";
cell2.innerHTML = "###";
cell3.innerHTML = rowID;
cell4.innerHTML = "<button id=''>Remove</button>";
}
var rowID = 0;
function myFunction() {
rowID++;
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);
//rowID=1;
cell1.innerHTML = "###";
cell2.innerHTML = "###";
cell3.innerHTML = rowID;
cell4.innerHTML = "<button id=''>Remove</button>";
}
Initialize the var rowID to 0 during declaration (considered good practice)
You made a silly mistake of assigning the rowid in the function itself.
jsFiddle: https://jsfiddle.net/z51z3jj1/2/
You are setting rowID=1 so every time it will have value 1. Also you need to set rowID=0 if you want to increment it otherwise if you don'y initialize it it will result in NaN
<script>
var rowID;
function myFunction() {
rowID++;
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);
rowID=1;
cell1.innerHTML = "###";
cell2.innerHTML = "###";
cell3.innerHTML = rowID;
cell4.innerHTML = "<button id="+rowID+" onclick='Remove(this)'>Remove</button>";
}
function Remove(btn){
btn.parentElement.parentElement.remove();
}
Here is jsfiddle
If you want remove elements, this is an option
row.setAttribute("onclick","remove(this)");
https://jsfiddle.net/z51z3jj1/4/

How to display dynamically added form data in a table in a different webpage when the data is saved in the local storage using purely javascript?

I'm doing a school project in which I'm creating web pages to allow users to input and then display it on another page. I am only using JavaScript, HTML and CSS for the web pages.
On the "Create An Event" page there is a form. I have saved all the input into local storage but now I am not sure how to retrieve the data to display it on the "Events Created" page (which shows the past events that the user has created).
Here is my JavaScript code:
document.addEventListener("DOMContentLoaded", docIsReady);
var eventHist;
function docIsReady() {
eventHist = localStorage.getItem("createEvent");
if (eventHist == null) {
eventHist = [];
} else {
eventHist = JSON.parse(eventHist);
}
//building of the table
for (var i = 0; i < eventHist.length; i++) {
var row = document.getElementById("list").insertRow(-1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
var cell5 = row.insertCell(4);
var cell6 = row.insertCell(5);
cell1.innerHTML = eventHist[i].name;
cell2.innerHTML = eventHist[i].positions;
cell3.innerHTML = eventHist[i].venue;
cell4.innerHTML = eventHist[i].date;
cell5.innerHTML = eventHist[i].timeStart;
cell6.innerHTML = eventHist[i].timeEnd;
}
}
function addHistory() {
var obj;
var name = document.getElementById("name").value;
if (!checkExisting(name)) {
var positions = document.getElementById("pos").value;
var venue = document.getElementById("venue").value;
var date = document.getElementById("date").value;
var starttime = document.getElementById("timeStart").value;
var endtime = document.getElementById("timeEnd").value;
obj = {
"name": name,
"venue": venue,
"date": date,
"timeStart": starttime,
"timeEnd": endtime
};
eventHist.push(obj)
localStorage.setItem("createEvent", JSON.stringify(obj));
}
//add to table
var row = document.getElementById("list").insertRow(-1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
var cell5 = row.insertCell(4);
var cell6 = row.insertCell(5);
cell1.innerHTML = obj.name;
cell2.innerHTML = obj.positions;
cell3.innerHTML = obj.venue;
cell4.innerHTML = obj.date;
cell5.innerHTML = obj.timeStart;
cell6.innerHTML = obj.timeEnd;
}
function sortTable() {
eventHist.sort(function(obj1, obj2) {
if (obj1.date > obj2.date)
return 1;
else if (obj1.date < obj2.date)
return -1;
else
return 0;
});
console.log("Sorted");
//reload table
var tableRow = document.querySelectorAll("#list tr");
console.log(tableRow);
console.log("no of rows=" + tableRow.length);
for (var i = 0; i < eventHist.length; i++) {
var row = document.getElementById("list").insertRow(-1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
var cell5 = row.insertCell(4);
var cell6 = row.insertCell(5);
cell1.innerHTML = eventHist[i].name;
cell2.innerHTML = eventHist[i].positions;
cell3.innerHTML = eventHist[i].venue;
cell4.innerHTML = eventHist[i].date;
cell5.innerHTML = eventHist[i].timeStart;
cell6.innerHTML = eventHist[i].timeEnd;
}
document.getElementById("list").style.display = "table";
}
Here is my HTML code:
<table border="1px" id="list" onload="addRow();">
<tr>
<th>Name of event</th>
<th>Positions</th>
<th>Venue</th>
<th>Date</th>
<th>Start Time</th>
<th>End Time</th>
<!--<th>Points Awarded</th>-->
</tr>
</table>

Checkbox checked property is undefined

I am adding rows and cols to html table programatically using Javascript:
for (var i = 0; i < results.length; i++) {
table = document.getElementById("EntityRecords");
rowCount = table.rows.length;
row = table.insertRow(rowCount);
row.id = results[i].LeadId;
row.className = "EntityRecordsRow";
cell1 = row.insertCell(0);
element = document.createElement("input");
element.type = "checkbox";
element.name = "chkbox[]";
cell1.appendChild(element);
cell1.className = "EntityRecordsCol";
cell2 = row.insertCell(1);
cell2.innerHTML = results[i].FirstName + " " + results[i].LastName;
}
On button click event, I need to find selected checkbox. I am reading the table cells using below code but checkbox cell checked property is undefined:
function OnRecordSelectionBtnClick() {
var table = document.getElementById("EntityRecords");
for (var i = 0, row; row = table.rows[i]; i++) {
var col = row.cells[0];
if (col.checked) {
var selectedText = row.cells[1].innerHTML;
alert(selectedText);
}
}
}
Any suggestions?
if ( col.firstElementChild.checked ), not if ( col.checked ). col is td element and its first child is input that has checked property.

Categories