Javascript Dynamic Table - javascript

I'm having trouble the following table should read r1 c1, r1 c2, r2 c1, r2 c2 and so on in each box within the table and user should only be able to pick up to 12 rows and 12 columns anything over that should display an error message. Here is my code so far.
<!DOCTYPE html>
<!-- written by Angela Bauer on 1/23/2013-->
<!-- saved from url=(0014)about:internet -->
<html>
<head>
<meta charset = "utf-8">
<title> Dynamic Table </title>
<script type = "text/javascript">
var width = 500;
var height = 500;
function CreateTable(txtRows, txtCols, hold)
{
if(validNumber(txtRows) && validNumber(txtCols)
&& (hold != null) && (hold.canHaveChildren))
{
hold.innerHTML = "";
var table = document.createElement("table");
table.border = 3;
table.borderColor = "Blue";
table.height = height;
table.width = width;
var row = null;
var cell = null;
hold.appendChild(table);
for(i=0; i<txtRows; i++)
{
row = appendR(table)
for(j=0; j<txtCols; j++)
{
cell = appendC(row);
cell.innerText = j;
cell = null;
}
row = null;
}
}
}
function appendR(table)
{
if(table != null)
{
return table.insertRow();
}
else
{
alert("Error while creating table. Cause: Container Table is null!");
}
}
function appendC(aRow)
{
if(aRow != null)
{
return aRow.insertCell();
}
else
{
alert("Error while creating table. Cause: Container row is null!");
}
}
function validNumber(ipNum)
{
if(isNaN(ipNum))
{
alert("Invalid Number!");
return false;
}
else if(ipNum <= 1)
{
alert("You can only enter a number from 1 - 12!");
return false;
}
else
{
return true;
}
}
</script>
</head>
<body>
<table>
<tr>
<td> How many Rows would you like: </td>
<td><input type=text name=txtRows value=1 /></td>
</tr>
<tr>
<td> How many Columns would you like: </td>
<td><input type=text name=txtCols value=1 /> </td>
</tr>
<tr>
<td colspan=10 align=right><input type=button name=cmdCreate value="Create Table"
onClick="CreateTable(txtRows.value, txtCols.value, divHolder)" /></td>
</tr>
</table>
<div id=divHolder></div>
</body>
</html>

As gdoron put you need to ask a question but im taking a punt and guess you want you code fixed.
Below is a working copy of you code. There was a ton of stuff wrong including
No ID's on the input boxes
No " used for the value of items within the HTML form
.insertRow was missing a parameter
.insertCell was missing a parameter
The validNumber function was producing an error if you entered the
number 1.
canHaveChildren is only valid in IE i have removed it but if your
script is going to be used in IE only then add it back
Things to be avoid for best practice:
using the words table, row etc as var names.
I guessing your new at this so my advice is to install Firefox and the firebug add on as it would have told you half the errors you were getting.
Also if its not doing what you want add alerts to sections of the code and work out where it is getting to or not getting to.
Hopefully this will get you on track.
<html>
<head>
<meta charset = "utf-8">
<title> Dynamic Table </title>
<script type = "text/javascript">
var width = 500;
var height = 500;
function createTable(txtRows, txtCols, hold) {
// alert (txtRows+", "+txtCols+", "+hold);
// alert (hold.canHaveChildren);
// Removed as its an IE only javascript ---- && (hold.canHaveChildren)
if(validNumber(txtRows) && validNumber(txtCols) && (hold != null) ) {
// alert ("is valid");
hold.innerHTML = "";
var table1 = document.createElement("table");
table1.border = 3;
table1.borderColor = "Blue";
table1.height = height;
table1.width = width;
var row1 = null;
var cell1 = null;
hold.appendChild(table1);
for(i=0; i<txtRows; i++) {
// alert ("first for");
row1 = appendR(table1, i);
for(j=0; j<txtCols; j++) {
// alert ("second for");
cell1 = appendC(row1, j);
cell1.innerText = j;
cell1 = null;
}
row1 = null;
}
}
}
function appendR(table1, i) {
if(table1 != null) {
return table1.insertRow(i);
} else {
alert("Error while creating table. Cause: Container Table is null!");
}
}
function appendC(aRow, j) {
if(aRow != null) {
return aRow.insertCell(j);
} else {
alert("Error while creating table. Cause: Container row is null!");
}
}
function validNumber(ipNum) {
if(isNaN(ipNum)) {
alert("Invalid Number!");
return false;
} else if(ipNum > 12) {
alert("You can only enter a number from 1 - 12!");
return false;
} else if(ipNum < 1) {
alert("You can only enter a number from 1 - 12!");
return false;
} else {
return true;
}
}
</script>
</head>
<body>
<table>
<tr>
<td> How many Rows would you like: </td>
<td><input id="txtRows" type="text" name="txtRows" value="1" /></td>
</tr>
<tr>
<td> How many Columns would you like: </td>
<td><input id="txtCols" type="text" name="txtCols" value="1" /> </td>
</tr>
<tr>
<td colspan=10 align=right><input type=button name=cmdCreate value="Create Table"
onClick="createTable(txtRows.value, txtCols.value, divHolder)" /></td>
</tr>
</table>
<div id="divHolder"></div>
</body>

Related

"Undefined is not an object" When trying to reference a cell in HTML

I'm trying to make a table with data from the user on a website. I added the option to erase the row but I get an error
"undefined is not an object (evaluating 'table.rows[i].cells[3]')"
My code works if I use a fixed table, but with the script to make the table editable it doesn't work, here is my code:
<html>
<head>
<title>Remove HTML Table Selected Row</title>
<meta charset="windows-1252">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
td:last-child{background-color: #F00;color:#FFF;cursor: pointer;
font-weight: bold;text-decoration: underline}
</style>
</head>
<body>
<div class="container">
<div class="tab tab-1">
<table id="table" border="1">
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Age</th>
<th>Delete</th>
</tr>
<tr>
</tr>
</table>
</div>
<div class="tab tab-2">
First Name :<input type="text" name="fname" id="fname">
Last Name :<input type="text" name="lname" id="lname">
Age :<input type="number" name="age" id="age">
<button onclick="addHtmlTableRow();">Add</button>
</div>
</div>
<script>
var rIndex,
table = document.getElementById("table");
// check the empty input
function checkEmptyInput()
{
var isEmpty = false,
fname = document.getElementById("fname").value,
lname = document.getElementById("lname").value,
age = document.getElementById("age").value;
if(fname === ""){
alert("First Name Connot Be Empty");
isEmpty = true;
}
else if(lname === ""){
alert("Last Name Connot Be Empty");
isEmpty = true;
}
else if(age === ""){
alert("Age Connot Be Empty");
isEmpty = true;
}
return isEmpty;
}
// add Row
function addHtmlTableRow()
{
// get the table by id
// create a new row and cells
// get value from input text
// set the values into row cell's
if(!checkEmptyInput()){
var newRow = table.insertRow(table.length),
cell1 = newRow.insertCell(0),
cell2 = newRow.insertCell(1),
cell3 = newRow.insertCell(2),
cell4 = newRow.insertCell(3),
fname = document.getElementById("fname").value,
lname = document.getElementById("lname").value,
age = document.getElementById("age").value,
edit = "Edit"
cell1.innerHTML = fname;
cell2.innerHTML = lname;
cell3.innerHTML = age;
cell4.innerHTML = edit;
// call the function to set the event to the new row
selectedRowToInput();
}
}
// display selected row data into input text
function selectedRowToInput()
{
for(var i = 1; i < table.rows.length; i++)
{
table.rows[i].onclick = function()
{
// get the seected row index
rIndex = this.rowIndex;
document.getElementById("fname").value = this.cells[0].innerHTML;
document.getElementById("lname").value = this.cells[1].innerHTML;
document.getElementById("age").value = this.cells[2].innerHTML;
};
}
}
selectedRowToInput();
var index, table = document.getElementById('table');
for(var i = 1; i < table.rows.length; i++)
{
table.rows[i].cells[3].onclick = function() //Line with the error
{
var c = confirm("do you want to delete this row");
if(c === true)
{
index = this.parentElement.rowIndex;
table.deleteRow(index);
}
//console.log(index);
};
}
</script>
</body>
</html>
Any ideas what might the problem be?, Thanks a lot
you don't need to loop inside function addHtmlTableRow() just add class to the Edit then setup event handler for dynamically added element using
document.addEventListener('click',function(e){
if(e.target){
//do something
}
});
var rIndex,
table = document.getElementById("table");
// check the empty input
function checkEmptyInput() {
var isEmpty = false,
fname = document.getElementById("fname").value,
lname = document.getElementById("lname").value,
age = document.getElementById("age").value;
if (fname === "") {
alert("First Name Connot Be Empty");
isEmpty = true;
} else if (lname === "") {
alert("Last Name Connot Be Empty");
isEmpty = true;
} else if (age === "") {
alert("Age Connot Be Empty");
isEmpty = true;
}
return isEmpty;
}
// add Row
function addHtmlTableRow() {
// get the table by id
// create a new row and cells
// get value from input text
// set the values into row cell's
if (!checkEmptyInput()) {
var newRow = table.insertRow(table.length),
cell1 = newRow.insertCell(0),
cell2 = newRow.insertCell(1),
cell3 = newRow.insertCell(2),
cell4 = newRow.insertCell(3),
fname = document.getElementById("fname").value,
lname = document.getElementById("lname").value,
age = document.getElementById("age").value,
edit = 'Edit';
cell1.innerHTML = fname;
cell2.innerHTML = lname;
cell3.innerHTML = age;
cell4.innerHTML = edit;
cell4.className = "delete"; // <== add this class
// call the function to set the event to the new row
selectedRowToInput();
}
}
// display selected row data into input text
function selectedRowToInput() {
for (var i = 1; i < table.rows.length; i++) {
table.rows[i].onclick = function() {
// get the seected row index
rIndex = this.rowIndex;
document.getElementById("fname").value = this.cells[0].innerHTML;
document.getElementById("lname").value = this.cells[1].innerHTML;
document.getElementById("age").value = this.cells[2].innerHTML;
};
}
}
selectedRowToInput();
// for deleting row
document.addEventListener('click', function(e) {
if (e.target && e.target.classList.contains('delete')) {
if (confirm("do you want to delete this row")) {
e.target.parentElement.remove();
}
}
});
td:last-child {
background-color: #F00;
color: #FFF;
cursor: pointer;
font-weight: bold;
text-decoration: underline;
}
<div class="container">
<div class="tab tab-1">
<table id="table" border="1">
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Age</th>
<th>Delete</th>
</tr>
<tr>
</tr>
</table>
</div>
<div class="tab tab-2">
First Name :<input type="text" name="fname" id="fname">
Last Name :<input type="text" name="lname" id="lname">
Age :<input type="number" name="age" id="age">
<button onclick="addHtmlTableRow();">Add</button>
</div>
</div>
Basically At the first iteration of the loop try to access third <td> (cell) which doesn't exist.
<table id="table" border="1">
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Age</th>
<th>Delete</th>
</tr>
<tr>
<!-- there is no cell -->
</tr>
</table>
Therefore undefined error shows up.
you can remove it as it has no use.
And
You should execute the loop after inserted some data into the table.
Just wrap the loop in a condition. (if you remove the <tr> then our condition should be table.rows.length > 1)
if(table.rows.length > 2){
for(var i = 1; i < table.rows.length; i++)
{
table.rows[i].cells[3].onclick = function()
{
var c = confirm("do you want to delete this row");
if(c === true)
{
index = this.parentElement.rowIndex;
table.deleteRow(index);
}
//console.log(index);
};
}
}
Arrays in Javascript starts at 0. In your example, this means that:
- rows[0] = Header row
- rows[1] = First data row
- rows[2] = Second data row
And so forth. Your for loop starts counting a 1.
Therefore, your for loop tries to access the second row in the table, but when the page first loads, this row doesn't contain any cells.
This is why the script says that undefined is not an object. The for loop will try to access row[1].cells[3] but row[1] doesn't have any cells. So, you're trying to access a cell that doesn't exist.

Javascript how do I get values from generated cells in HTML table?

I have a table (check screenshot) where I can generate rows and the second column will contain a number from a text field. I want to be able to grab that number from a generated cell and perform calculations with it. I am not entirely sure how to target the cell that gets generated given I can generate X amount of rows. The principle for this table is to generate numbers from a text field and then press a button and the third column will display a sum of all previous second column values. The execution will start after a button is pressed which I will add later
var counter = 1;
var pNum = 0;
var i;
//Target elements
let btnAdd = document.getElementById('btn');
let testBtn = document.getElementById('test');
let table = document.getElementById('table1');
let bTimeInput = document.querySelector('#bTime')
let bValue = document.querySelector('bCell');
//check for empty value
function checkForEmpty(input) {
if(input.value == null || input.value == undefined || input.value.length == 0) {
return true;
}
return false;
}
btnAdd.addEventListener('click', () => {
if(checkForEmpty(bTimeInput)) {
alert('Enter a number')
} else {
counter++;
pNum++;
let bTime = bTimeInput.value;
let wTime = 'dummyValue';
let taTime = 0;
let template = `
<tr>
<td>${pNum}</td>
<td>${bTime}</td>
<td>${wTime}</td>
</tr>`;
table.innerHTML += template;
}
});
<!DOCTYPE html>
<html lang="en">
<head>
<title>FCFS CPU Scheduling Algorithm</title>
<link rel="stylesheet" href="main.css">
</head>
<body>
<div class="container">
<div id="data">
<input type="number" id="bTime" placeholder="enter burst time">
<button id="btn">Add process</button>
</div>
<table id="table1">
<tr>
<th>P#</th>
<th id="bCell">burst time</th>
<th>wait time</th>
<th>t/a time</th>
</tr>
</table>
</div>
<script src="algorithm.js"></script>
</body>
</html>
So I added some class and row pointers to help out. see what you think.
var counter = 0;
var pNum = 0;
var i;
//Target elements
let btnAdd = document.getElementById('btn');
let testBtn = document.getElementById('test');
let table = document.getElementById('table1');
let bTimeInput = document.querySelector('#bTime')
let bValue = document.querySelector('bCell');
//check for empty value
function checkForEmpty(input) {
if(input.value == null || input.value == undefined || input.value.length == 0) {
return true;
}
return false;
}
const getTotalTime = (bTime, counter) => {
if (counter === 1) return bTime;
const { innerText: pTime } = document.querySelector(`tr.row${counter-1} td.col4`);
return parseInt(bTime, 10) + parseInt(pTime, 10);
};
btnAdd.addEventListener('click', () => {
if(checkForEmpty(bTimeInput)) {
alert('Enter a number')
} else {
counter++;
pNum++;
let bTime = bTimeInput.value;
let wTime = 'dummyValue';
let taTime = 0;
let template = `
<tr class="row${counter}">
<td class="col1">${pNum}</td>
<td class="col2">${bTime}</td>
<td class="col3">${wTime}</td>
<td class="col4">${getTotalTime(bTime, counter)}</td>
</tr>`;
table.innerHTML += template;
}
});
<!DOCTYPE html>
<html lang="en">
<head>
<title>FCFS CPU Scheduling Algorithm</title>
<link rel="stylesheet" href="main.css">
</head>
<body>
<div class="container">
<div id="data">
<input type="number" id="bTime" placeholder="enter burst time">
<button id="btn">Add process</button>
</div>
<table id="table1">
<tr>
<th>P#</th>
<th id="bCell">burst time</th>
<th>wait time</th>
<th>t/a time</th>
</tr>
</table>
</div>
<script src="algorithm.js"></script>
</body>
</html>
Here is a version that takes on board with Chris G mentions about seperation.
var counter = 0;
var pNum = 0;
var i;
const data = {
points: []
};
const headerTemplate = () => `
<tr>
<th>P#</th>
<th id="bCell">burst time</th>
<th>wait time</th>
<th>t/a time</th>
</tr>
`;
const rowTemplate = ({id, bTime, wTime, tTime}) => `
<tr>
<td>${id}</td>
<td>${bTime}</td>
<td>${wTime}</td>
<td>${tTime}</td>
</tr>
`;
//Target elements
let btnAdd = document.getElementById('btn');
let testBtn = document.getElementById('test');
let table = document.getElementById('table1');
let bTimeInput = document.querySelector('#bTime')
let bValue = document.querySelector('bCell');
//check for empty value
function checkForEmpty(input) {
if(input.value == null || input.value == undefined || input.value.length == 0) {
return true;
}
return false;
}
const getTotalTime = (bTime) => {
if (data.points.length === 0) return bTime;
return bTime + data.points[data.points.length-1].tTime;
};
const drawTable = () => data.points.map(point => rowTemplate(point)).join('');
btnAdd.addEventListener('click', () => {
if(checkForEmpty(bTimeInput)) {
alert('Enter a number')
} else {
counter ++;
const bTime = parseInt(bTimeInput.value);
const newDataPoint = {
id: counter,
bTime,
wTime: 'dummyValue',
tTime: getTotalTime(bTime)
};
data.points.push(newDataPoint);
table.innerHTML = headerTemplate() + drawTable(data);
}
});
<!DOCTYPE html>
<html lang="en">
<head>
<title>FCFS CPU Scheduling Algorithm</title>
<link rel="stylesheet" href="main.css">
</head>
<body>
<div class="container">
<div id="data">
<input type="number" id="bTime" placeholder="enter burst time">
<button id="btn">Add process</button>
</div>
<table id="table1">
</table>
</div>
<script src="algorithm.js"></script>
</body>
</html>
The exact answer to your problem cannot be given without code snippets but here is an approach which I thought of:
You can use the
const cells=document.querySelectorAll('td')
to get a node list of all the elements and then target specific cells by indexing this list. Then you can extract value from those node elements by
cells[index].innerText
or
cells[index].innerHTML
and perform operations on it.
var counter = 1;
var pNum = 0;
var i;
//Target elements
let btnAdd = document.getElementById('btn');
let testBtn = document.getElementById('test');
let table = document.getElementById('table1');
let bTimeInput = document.querySelector('#bTime')
let bValue = document.querySelector('bCell');
//check for empty value
function checkForEmpty(input) {
if(input.value == null || input.value == undefined || input.value.length == 0) {
return true;
}
return false;
}
var x0=[]//array for saving
btnAdd.addEventListener('click', () => {
if(checkForEmpty(bTimeInput)) {
alert('Enter a number')
} else {
counter++;
pNum++;
let bTime = bTimeInput.value;
let wTime = 'dummyValue';
let taTime = 0;
//extremely long but successful traceable tags begin
var x1=document.createElement('tr')
table.appendChild(x1)//parent element in proper place
//now to create children
var x2=document.createElement('td')
var x3=document.createElement('td')
var x4=document.createElement('td')
//now to apply data to children
x2.innerText=pNum
x3.innerText=bTime
x4.innerText=wTime
//now to deploy the children
x1.appendChild(x2)
x1.appendChild(x3)
x1.appendChild(x4)
//extremely long but successful traceable tags end
//now to place in array
x0.push({x1:x1,x2:x2,x3:x3,x4:x4})
console.log(x0[x0.length-1])
}
});
<!DOCTYPE html>
<html lang="en">
<head>
<title>FCFS CPU Scheduling Algorithm</title>
<link rel="stylesheet" href="main.css">
</head>
<body>
<div class="container">
<div id="data">
<input type="number" id="bTime" placeholder="enter burst time">
<button id="btn">Add process</button>
</div>
<table id="table1">
<tr>
<th>P#</th>
<th id="bCell">burst time</th>
<th>wait time</th>
<th>t/a time</th>
</tr>
</table>
</div>
<script src="algorithm.js"></script>
</body>
</html>

Show only selected row in table and other row will hide on same time use Javascript

It is a room type selection. Here I want to select room type on this selection I want to show only that row which I was selected from dropdown and other row should be hide at same time.
<select onChange="onSelect(this)" class="col-Room" name="ACRoom">
<option value="optionAC" >AC-Room</option>
<option value="optionNAC">Non AC-Room</option>
</select>
This is javascript code which I am using for selection. But it is not working properly. Only second option is working on select and first option is not working properly on selection.
Please help me out.
<script>
function onSelect(thisselect) {
var selected = thisselect.options[thisselect.selectedIndex].value;
toggleRow(selected);
}
function toggleRow(id) {
var row = document.getElementById(id);
if (row.style.display == '') {
row.style.display = 'none';
}
else {
row.style.display = '';
}
}
function showRow(id) {
var row = document.getElementById(id);
row.style.display = '';
}
function hideRow(id) {
var row = document.getElementById(id);
row.style.display = 'none';
}
function hideAll() {
hideRow('optionAC');
hideRow('optionNAC');
}
</script>
You should hide other rows while showing some particular rows. While selecting first option, you are not hiding nonac rows. Also I suggest you to use classs names instead of ID, since table can have multiple ac/non-ac rows. The below code could help you.
<!DOCTYPE html>
<table id="table">
<thead>
<tr>
<th>Rooms</th>
</tr>
</thead>
<tbody>
<tr class="ac">
<td>AC room</td>
</tr>
<tr class="nonac">
<td>Non Ac room</td>
</tr>
<tr class="ac">
<td>AC room</td>
</tr>
<tr class="nonac">
<td>Non Ac room</td>
</tr>
</tbody>
</table>
<select onChange="onSelect(this)">
<option value="ac">AC</option>
<option value="nonac">NON AC</option>
</select>
<script>
var ac = document.getElementsByClassName("ac");
var nonac = document.getElementsByClassName("nonac");
function onSelect(thisselect) {
var selected = thisselect.options[thisselect.selectedIndex].value;
toggleRow(selected);
}
function toggleRow(id) {
if (id == "ac") {
showac();
} else {
shownonac();
}
}
function showac() {
for (var i = 0; i < nonac.length; i += 1) {
nonac[i].style.display = 'none';
}
for (var i = 0; i < ac.length; i += 1) {
ac[i].style.display = 'block';
}
}
function shownonac() {
for (var i = 0; i < ac.length; i += 1) {
ac[i].style.display = 'none';
}
for (var i = 0; i < nonac.length; i += 1) {
nonac[i].style.display = 'block';
}
}
</script>

Unsure as to how to go about deleting the (highlighted/selected row) in table

How do I go about either modifying the existing Javascript code or add some code to be able to have the option to delete the highlighted (selected row) from my HTML table at the click of a button?
The use of jQuery is framework also fine.
<!DOCTYPE html>
<html>
<head>
<title>Table Row Demo</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<style type="text/css">
tr.normal td {
color: black;
background-color: white;
}
tr.highlighted td {
color: white;
background-color: red;
}
</style>
<script type="text/javascript">
window.onload = function() {
test()
}
function test() {
var trows = document.getElementById('mstrTable').rows, t = trows.length, trow, nextrow,
rownum = document.getElementById('rownum'),
addEvent = (function(){return window.addEventListener? function(el, ev, f){
el.addEventListener(ev, f, false); //modern browsers
}:window.attachEvent? function(el, ev, f){
el.attachEvent('on' + ev, function(e){f.apply(el, [e]);}); //IE 8 and less
}:function(){return;}; //a very old browser (IE 4 or less, or Mozilla, others, before Netscape 6), so let's skip those
})();
rownum.value = rownum.defaultValue; //reset for browsers that remember input values on reload
while (--t > -1) {
trow = trows[t];
trow.className = 'normal';
addEvent(trow, 'click', highlightRow);
}//end while
function highlightRow(gethighlight) { //now dual use - either set or get the highlighted row
gethighlight = gethighlight === true;
var t = trows.length;
while (--t > -1) {
trow = trows[t];
if(gethighlight && trow.className === 'highlighted'){return t;}
else if (!gethighlight){
if(trow !== this) { trow.className = 'normal'; }
else if(this.className === 'normal') { rownum.value = t; }
else { rownum.value = rownum.defaultValue; }
}
}//end while
return gethighlight? null : this.className = this.className === 'highlighted'? 'normal' : 'highlighted';
}//end function
function movehighlight(way, e){
e.preventDefault && e.preventDefault();
e.returnValue = false;
var idx = highlightRow(true); //gets current index or null if none highlighted
if(typeof idx === 'number'){//there was a highlighted row
idx += way; //increment\decrement the index value
if(idx && (nextrow = trows[idx])){ return highlightRow.apply(nextrow); } //index is > 0 and a row exists at that index
else if(idx){ return highlightRow.apply(trows[1]); } //index is out of range high, go to first row
return highlightRow.apply(trows[trows.length - 1]); //index is out of range low, go to last row
}
return highlightRow.apply(trows[way > 0? 1 : trows.length - 1]); //none was highlighted - go to 1st if down arrow, last if up arrow
}//end function
function processkey(e){
switch(e.keyCode){
case 38: {//up arrow
return movehighlight(-1, e)
}
case 40: {//down arrow
return movehighlight(1, e);
}
default: {
return true;
}
}
}//end function
addEvent(document, 'keydown', processkey);
addEvent(window, 'unload', function(){}); //optional, resets the page for browsers that remember the script state on back and forward buttons
}//end function
</script>
</head>
<body>
<div>
Current Row: <input type="text" id="rownum" value="None" readonly>
<table id="mstrTable" cellspacing="0" border="1">
<thead>
<tr>
<th>File Number</th>
<th>Date1</th>
<th>Date2</th>
<th>Status</th>
<th>Num.</th>
</tr>
</thead>
<tbody>
<tr>
<td>KABC</td>
<td>09/12/2002</td>
<td>09/12/2002</td>
<td>Submitted</td>
<td>1</td>
</tr>
<tr>
<td>KCBS</td>
<td>09/11/2002</td>
<td>09/11/2002</td>
<td>Lockdown</td>
<td>2</td>
</tr>
<tr>
<td>WFLA</td>
<td>09/11/2002</td>
<td>09/11/2002</td>
<td>Submitted</td>
<td>3</td>
</tr>
<tr>
<td>WTSP</td>
<td>09/15/2002</td>
<td>09/15/2002</td>
<td>In-Progress</td>
<td>4</td>
</tr>
</tbody>
</table>
</div>
<br><br>
<input type="button" value="delete this row" onclick="delete_row()"/>
</body>
</html>
this seems to work, once the row number seems to accounted for.
function delete_row() {
var r = document.getElementById("rownum").value
document.getElementById("mstrTable").deleteRow(r);
}
Use this (if you know the row number)
function delete_row() {
var r = document.getElementById("rownum").value
document.getElementById("mstrTable").deleteRow(r);
}
This only deletes a row that is selected. No need to pass in the row number.
function delete_row() {
document.querySelector(".highlighted").remove();
}
You can see it working here: http://jsbin.com/gubuduli/3/edit?html,output

Insert multiple rows and columns to a table in html dynamically using javascript code

I am trying to insert multiple rows and columns to create a table in html dynamically by selecting the number of rows and columns in dropdown list using javascript code like in MS Word.
For example if I select number of rows as 5 and number of columns as 5 from the dropdown list of numbers. 5 rows and 5 columns should get displayed.
My question is how can I add multiple rows and columns dynamically to create a table by selecting the number of rows and columns from the drop down list.
Since, <table> element is the one of the most complex structures in HTML, HTML DOM provide new interface HTMLTableElement with special properties and methods for manipulating the layout and presentation of tables in an HTML document.
So, if you want to accomplish expected result using DOM standards you can use something like this:
Demo old
Demo new
HTML:
<ul>
<li>
<label for="column">Add a Column</label>
<input type="number" id="column" />
</li>
<li>
<label for="row">Add a Row</label>
<input type="number" id="row" />
</li>
<li>
<input type="button" value="Generate" id="btnGen" />
<input type="button" value="Copy to Clipboard" id="copy" />
</li>
</ul>
<div id="wrap"></div>
JS new:
JavaScript was improved.
(function (window, document, undefined) {
"use strict";
var wrap = document.getElementById("wrap"),
setColumn = document.getElementById("column"),
setRow = document.getElementById("row"),
btnGen = document.getElementById("btnGen"),
btnCopy = document.getElementById("btnCopy");
btnGen.addEventListener("click", generateTable);
btnCopy.addEventListener("click", copyTo);
function generateTable(e) {
var newTable = document.createElement("table"),
tBody = newTable.createTBody(),
nOfColumns = parseInt(setColumn.value, 10),
nOfRows = parseInt(setRow.value, 10),
row = generateRow(nOfColumns);
newTable.createCaption().appendChild(document.createTextNode("Generated Table"));
for (var i = 0; i < nOfRows; i++) {
tBody.appendChild(row.cloneNode(true));
}
(wrap.hasChildNodes() ? wrap.replaceChild : wrap.appendChild).call(wrap, newTable, wrap.children[0]);
}
function generateRow(n) {
var row = document.createElement("tr"),
text = document.createTextNode("cell");
for (var i = 0; i < n; i++) {
row.insertCell().appendChild(text.cloneNode(true));
}
return row.cloneNode(true);
}
function copyTo(e) {
prompt("Copy to clipboard: Ctrl+C, Enter", wrap.innerHTML);
}
}(window, window.document));
JS old:
(function () {
"use strict";
var wrap = document.getElementById("wrap"),
setColumn = document.getElementById("column"),
setRow = document.getElementById("row"),
btnGen = document.getElementById("btnGen"),
copy = document.getElementById("copy"),
nOfColumns = -1,
nOfRows = -1;
btnGen.addEventListener("click", generateTable);
copy.addEventListener("click", copyTo);
function generateTable(e) {
var newTable = document.createElement("table"),
caption = newTable.createCaption(),
//tHead = newTable.createTHead(),
//tFoot = newTable.createTFoot(),
tBody = newTable.createTBody();
nOfColumns = parseInt(setColumn.value, 10);
nOfRows = parseInt(setRow.value, 10);
caption.appendChild(document.createTextNode("Generated Table"));
// appendRows(tHead, 1);
// appendRows(tFoot, 1);
appendRows(tBody);
(wrap.hasChildNodes() ? wrap.replaceChild : wrap.appendChild).call(wrap, newTable, wrap.firstElementChild);
}
function appendColumns(tElement, count) {
var cell = null,
indexOfRow = [].indexOf.call(tElement.parentNode.rows, tElement) + 1,
indexOfColumn = -1;
count = count || nOfColumns;
for (var i = 0; i < count; i++) {
cell = tElement.insertCell(i);
indexOfColumn = [].indexOf.call(tElement.cells, cell) + 1;
cell.appendChild(document.createTextNode("Cell " + indexOfColumn + "," + indexOfRow));
}
}
function appendRows(tElement, count) {
var row = null;
count = count || nOfRows;
for (var i = 0; i < count; i++) {
row = tElement.insertRow(i);
appendColumns(row);
}
}
function copyTo(e) {
prompt("Copy to clipboard: Ctrl+C, Enter", wrap.innerHTML);
}
}());
If you want to copy generated result to clipboard you can look at answer of Jarek Milewski - How to copy to the clipboard in JavaScript?
You can use this function to generate dynamic table with no of rows and cols you want:
function createTable() {
var a, b, tableEle, rowEle, colEle;
var myTableDiv = document.getElementById("DynamicTable");
a = document.getElementById('txtRows').value; //No of rows you want
b = document.getElementById('txtColumns').value; //No of column you want
if (a == "" || b == "") {
alert("Please enter some numeric value");
} else {
tableEle = document.createElement('table');
for (var i = 0; i < a; i++) {
rowEle = document.createElement('tr');
for (var j = 0; j < b; j++) {
colEle = document.createElement('td');
rowEle.appendChild(colEle);
}
tableEle.appendChild(rowEle);
}
$(myTableDiv).html(tableEle);
}
}
Try something like this:
var
tds = '<td>Data'.repeat(col_cnt),
trs = ('<tr>'+tds).repeat(row_cnt),
table = '<table>' + trs + '</table>;
Then place the table in your container:
document.getElementById('tablePreviewArea').innerHTML = table;
Or with JQuery:
$('#tablePreviewArea').html(table);
Here is the JSFiddle using native js.
Here is the JSFiddle using jQuery.
About the string repeat function
I got the repeat function from here:
String.prototype.repeat = function( num )
{
return new Array( num + 1 ).join( this );
}
I had one sample code...try this and modify it according to your requirement. May it helps you out.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Untitled Document</title>
<style type="text/css">
#mytab td{
width:100px;
height:20px;
background:#cccccc;
}
</style>
<script type="text/javascript">
function addRow(){
var root=document.getElementById('mytab').getElementsByTagName('tbody')[0];
var rows=root.getElementsByTagName('tr');
var clone=cloneEl(rows[rows.length-1]);
root.appendChild(clone);
}
function addColumn(){
var rows=document.getElementById('mytab').getElementsByTagName('tr'), i=0, r, c, clone;
while(r=rows[i++]){
c=r.getElementsByTagName('td');
clone=cloneEl(c[c.length-1]);
c[0].parentNode.appendChild(clone);
}
}
function cloneEl(el){
var clo=el.cloneNode(true);
return clo;
}
</script>
</head>
<body>
<form action="">
<input type="button" value="Add a Row" onclick="addRow()">
<input type="button" value="Add a Column" onclick="addColumn()">
</form>
<br>
<table id="mytab" border="1" cellspacing="0" cellpadding="0">
<tr>
<td> </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
</table>
</body>
</html>
Instead of button , you can use select menu and pass the value to variable. It will create row ,column as per the value.

Categories

Resources