I Create a Table Using this code,
<table class="table table-green table-hover" id="tblk"></table>
And I Use This JavaScrip Function (For A Button) to add Rows when I add data in to table,
function addRow() {
var custid = document.getElementById('InputCusomerID').value
var custname = document.getElementById('InputCusomerName').value
var itemid = document.getElementById('InputItemID').value
var table = document.getElementById('tblk')
var row = table.insertRow(0)
var cell1 = row.insertCell(0)
var cell2 = row.insertCell(1)
var cell3 = row.insertCell(2)
cell1.innerHTML = custid
cell2.innerHTML = custname
cell3.innerHTML = itemid
}
When I clicked a table row, I need to get a table Row value into my input text field
This Is my JavaScrip Function to get table rows to value into my text field..,
var table = document.getElementById('tblk'),
rIndex
for (var i = 1; i < table.rows.length; i++) {
table.rows[i].onclick = function () {
document.getElementById('InputCusomerID').value = this.cells[0].innerHTML
document.getElementById('InputCusomerName').value = this.cells[1].innerHTML
document.getElementById('InputItemID').value = this.cells[2].innerHTML
}
}
But My Code Is Not Working I Can't Get Table Row Value Into My Text Field.
Can You Help Me With That Problem..?
Thank You Very Much..!
function addRow() {
var custid = document.getElementById('InputCusomerID').value
var custname = document.getElementById('InputCusomerName').value
var itemid = document.getElementById('InputItemID').value
var table = document.getElementById('tblk')
var row = table.insertRow(0)
var cell1 = row.insertCell(0)
var cell2 = row.insertCell(1)
var cell3 = row.insertCell(2)
cell1.innerHTML = custid
cell2.innerHTML = custname
cell3.innerHTML = itemid
}
var table = document.getElementById('tblk'),
rIndex
for (var i = 1; i < table.rows.length; i++) {
table.rows[i].onclick = function() {
document.getElementById('InputCusomerID').value = this.cells[0].innerHTML
document.getElementById('InputCusomerName').value = this.cells[1].innerHTML
document.getElementById('InputItemID').value = this.cells[2].innerHTML
}
}
<table class="table table-green table-hover" id="tblk"></table>
I don't know exactly what you're trying to do, but it's not working because your click listener is being called before your table is populated. See my code.
function addRow() {
var custid = document.getElementById('InputCusomerID').value
var custname = document.getElementById('InputCusomerName').value
var itemid = document.getElementById('InputItemID').value
var table = document.getElementById('tblk')
var row = table.insertRow(0)
var cell1 = row.insertCell(0)
var cell2 = row.insertCell(1)
var cell3 = row.insertCell(2)
cell1.innerHTML = custid
cell2.innerHTML = custname
cell3.innerHTML = itemid
setListeners();
}
var table = document.getElementById('tblk'),
rIndex;
function setListeners() {
for (var i = 0; i < table.rows.length; i++) {
table.rows[i].addEventListener('click', function (e) {
console.log(e.target);
document.getElementById('InputCusomerID').value = "result: " + this.cells[0].innerHTML
document.getElementById('InputCusomerName').value = "result: " + this.cells[1].innerHTML
document.getElementById('InputItemID').value = "result: " + this.cells[2].innerHTML
});
}
}
addRow();
<input type="text" id="InputCusomerID" value="a" />
<input type="text" id="InputCusomerName" value="b" />
<input type="text" id="InputItemID" value="c" />
<table class="table table-green table-hover" id="tblk"></table>
Related
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>
I'm trying to figure out how to add a new row to a table using Javascript but I also need to be able to add 3 columns into this table and here is where I am having problems. I can't seem to get it to work. Here is the javascript:
This adds rows with first field being ID entered into the first row but I don't know how to fill in columns.
function myCreateFunction() {
var table = document.getElementById("myTable");
var add = 1;
for (var i = 0; i < add; i++) {
var row = table.insertRow(2);
var cell1 = row.insertCell(0);
var div1 = document.createElement('div');
div1.innerHTML = "ID";
cell1.appendChild(div1);
div1.contentEditable = true;
}
}
Here is my Table:
<table id="myTable">
<tr>
<td>ID</td>
<td>First Name</td>
<td>Last Name</td>
<td>Add More</td>
</tr>
<tr>
<td>1</td>
<td>Jelly</td>
<td>Beans</td>
<td><button onclick="myCreateFunction()">Create row</button>
<button onclick="myDeleteFunction()">Delete row</button></td>
</tr>
</table>
try this
function myCreateFunction(thisObj) {
var buttonTr = thisObj.parentNode.parentNode;
var buttonTrHTML = buttonTr.outerHTML;
buttonTr.parentNode.removeChild(buttonTr);
var table = document.getElementById("myTable");
var add = 1;
for (var i = 0; i < add; i++)
{
table.innerHTML += "<tr><td>ID</td> <td>First Name</td><td>Last Name</td> <td>Add More</td><tr>";
}
//table.innerHTML += buttonTrHTML ;
table.appendChild(buttonTr );
}
and you need to pass the current Obj as
<button onclick="myCreateFunction(this)">Create row</button>
Try this
function myCreateFunction() {
var table = document.getElementById("myTable");
var rows = table.rows.length;
var row = table.insertRow(rows);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
cell1.innerHTML = "ID";
cell1.contentEditable = true;
cell2.innerHTML = "First Name";
cell2.contentEditable = true;
cell3.innerHTML = "Last Name";
cell3.contentEditable = true;
var but1 = document.createElement('button');
but1.innerHTML = "Create row";
but1.setAttribute("onclick", "myCreateFunction()");
cell4.appendChild(but1);
var but2 = document.createElement('button');
but2.innerHTML = "Delete row";
but2.setAttribute("onclick", "myDeleteFunction()");
cell4.appendChild(but2);
}
<table id="myTable">
<tr>
<td>ID</td>
<td>First Name</td>
<td>Last Name</td>
<td>Add More</td>
</tr>
<tr>
<td>1</td>
<td>Jelly</td>
<td>Beans</td>
<td><button onclick="myCreateFunction()">Create row</button><button onclick="myDeleteFunction()">Delete row</button></td>
</tr>
</table>
I solved this a bit different. And it works fine (also with deleting rows):
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var maxRows = 10;
if (rowCount < maxRows) {
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
for (var i = 0; i < colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[0].cells[i].innerHTML;
}
} else {
alert("Max. Tabs= " + maxRows);
}
}
function deleteRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
for (var i = 0; i < rowCount; i++) {
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
if (chkbox != null && chkbox.checked == true) {
if (rowCount <= 1) {
alert("Min Tabs = 1");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
}
Try following function
function myCreateFunction() {
var table = document.getElementById("myTable");
var rowCount = table.rows.length;
console.log(rowCount)
var row = table.insertRow(rowCount);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
cell1.innerHTML = rowCount;
cell2.innerHTML = ""; //put your text/html here
cell2.innerHTML = ""; //put your text/html here
}
put your desired text or html in innerHTML of the respected cell
Also for Pavel's answer your markup is wrong(though I haven't tested the function). The table id 'myTable' should be passed as string.
<button onclick="addRow('myTable')">Create row</button>
could not comment for not having enough reputation
Hope this helps.
I got this project for school, I need to load data from sessionStorage in a html table when my .html loads (not only from cache).
I insert new data in sessionStorage from another .html, i need to save it dynamically (for example the first row of my table is rfc0, razon_social0, direccion_fiscal0, the next row is rfc1, razon_social1, direccion_fiscal1, etc...), I use this Javascript function to save my data:
function getInfo() {
if (sessionStorage.contador){
var i = parseInt(sessionStorage.contador);
}
else{
sessionStorage.setItem('contador', "0");
var i = parseInt(sessionStorage.contador);
}
var rfc = document.getElementById('RFC').value.toUpperCase();
sessionStorage.setItem('rfc' + i, rfc);
var razon_social = document.getElementById('razon_social').value;
sessionStorage.setItem('razon_social' + i, razon_social);
var domicilio_fiscal = document.getElementById('domicilio_fiscal').value;
sessionStorage.setItem('domicilio_fiscal' + i, domicilio_fiscal);
var banco = document.getElementById('banco').value;
sessionStorage.setItem('banco' + i, banco);
var numero_cuenta = document.getElementById('numero_cuenta').value;
sessionStorage.setItem('numero_cuenta' + i, numero_cuenta);
i++;
sessionStorage.setItem('contador', i);
}
In my body onpageshow I use this function to check the Storage support and call the data:
function checkStorage() {
if(typeof(Storage) !== "undefined") {
if(sessionStorage.flag) {
agregarDatos();
}
}
else {
alert('Sorry! No Web Storage support...')
}
}
My function agregarDatos() is:
function agregarDatos() {
var table = document.getElementById("tabla_clientes");
var i = parseInt(sessionStorage.contador);
var conta = 0;
while(conta <= i){
var row = table.insertRow(-1);
var cell0 = row.insertCell(0)
var cell1 = row.insertCell(1);
var cell2 = row.insertCell(2);
var cell3 = row.insertCell(3);
var cell4 = row.insertCell(4);
cell0.innerHTML = '<input class="check" type="checkbox" onClick="validateButton()">';
cell1.innerHTML = sessionStorage.getItem('rfc' + conta);
cell2.innerHTML = sessionStorage.getItem('razon_social' + conta);
cell3.innerHTML = sessionStorage.getItem('domicilio_fiscal' + conta);
cell4.innerHTML = '<input class="editar" type="button" value="Editar">';
conta++;
}
}
When I test this, got nothing even when I add an element from the first time, I can't figure what's wrong.
If I save the data without ID I can only add one row with the last data stored.
P.D. Only I can use Javascript...
Your code has a couple of errors:
In order to populate the table you are checking the value of sessionStorage.flag that is not set anywhere in your code. As it is not defined, the if condition is false and agregarDatos() will never be called. To fix this check for sessionStorage.contador (as it is done in the JSFiddle specified below)
In agregarDatos() the loop goes one extra iteration because you are doing conta <= i when you should be doing conta < i.
This would be the code (with some mock HTML and getInfo call). The modified lines are pointed with comments:
function getInfo() {
if (sessionStorage.contador){
var i = parseInt(sessionStorage.contador);
} else {
sessionStorage.setItem('contador', "0");
var i = parseInt(sessionStorage.contador);
}
var rfc = document.getElementById('RFC').value.toUpperCase();
sessionStorage.setItem('rfc' + i, rfc);
var razon_social = document.getElementById('razon_social').value;
sessionStorage.setItem('razon_social' + i, razon_social);
var domicilio_fiscal = document.getElementById('domicilio_fiscal').value;
sessionStorage.setItem('domicilio_fiscal' + i, domicilio_fiscal);
var banco = document.getElementById('banco').value;
sessionStorage.setItem('banco' + i, banco);
var numero_cuenta = document.getElementById('numero_cuenta').value;
sessionStorage.setItem('numero_cuenta' + i, numero_cuenta);
i++;
sessionStorage.setItem('contador', i);
}
function agregarDatos() {
var table = document.getElementById("tabla_clientes");
var i = parseInt(sessionStorage.contador);
var conta = 0;
// Loop from 0 to elems-1 (before it was iterating one extra time)
while(conta < i){
var row = table.insertRow(-1);
var cell0 = row.insertCell(0)
var cell1 = row.insertCell(1);
var cell2 = row.insertCell(2);
var cell3 = row.insertCell(3);
var cell4 = row.insertCell(4);
cell0.innerHTML = '<input class="check" type="checkbox" onClick="validateButton()">';
cell1.innerHTML = sessionStorage.getItem('rfc' + conta);
cell2.innerHTML = sessionStorage.getItem('razon_social' + conta);
cell3.innerHTML = sessionStorage.getItem('domicilio_fiscal' + conta);
cell4.innerHTML = '<input class="editar" type="button" value="Editar">';
conta++;
}
}
function checkStorage() {
if(typeof(Storage) !== "undefined") {
// sessionStorage.flag does not exist, use a value that you know will exist
if(sessionStorage.contador) {
agregarDatos();
}
}
else {
alert('Sorry! No Web Storage support...')
}
}
window.onload = function() {
console.log(1);
checkStorage();
}
<div>
<input type="text" id="RFC" placeholder="RFC" /><br/>
<input type="text" id="razon_social" placeholder="Razón Social"/><br/>
<input type="text" id="domicilio_fiscal" placeholder="Domicilio Fiscal"/><br/>
<input type="text" id="banco" placeholder="Banco"/><br/>
<input type="text" id="numero_cuenta" placeholder="Número de Cuenta"/><br/>
<input type="button" value="Add to table" onclick="getInfo()"/>
</div>
<table id="tabla_clientes"></table>
That window is sandboxed so you cannot see it working on here, but you can on this JSFiddle.
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>
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.