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

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>

Related

To update LocalStorage values from a dynamically created HTML table

The HTML table is dynamically created with the function createTableRow(empDetail), which is working but when the rows/cells values are updated/changed it reflects in the HTML table but I want the same respective changed values to get changed in LocalStorage against the respective id. Help is needed for function tableUpdate()
Note: There is only one key i.e. empDetails and the same key has multiple id's of respective rows (Employee) created
"use strict";
let addNewEmployee = document.getElementById("addNewEmployee");
let modal = document.getElementById("favDialog");
let closeModal = document.getElementById("cancelModal");
let modalForm = document.getElementById("modal-form");
let submitModal = document.getElementById("submitModal");
let tableContainerHeader = document.querySelector(".table-container-header");
let tableContainerContent = document.querySelector(".table-container-content");
let empTable = document.getElementById("employeeTable");
const showModal = addNewEmployee.addEventListener("click", function() {
modal.showModal();
});
closeModal.addEventListener("click", function() {
modal.close();
});
let employeeId = document.getElementById("employeeId");
let employeeName = document.getElementById("employeeName");
let designation = document.getElementById("designation");
let salary = document.getElementById("salary");
let uniqueEmpId = document.getElementById("empDetailId");
let tr = null;
let empDetails = [];
if (localStorage.getItem("empDetails")) {
empDetails.map((empDetail) => {
createTableRow(empDetail);
});
}
let onModalSubmit = modal.addEventListener("submit", function(e) {
e.preventDefault();
if (tr == null) {
if (employeeId && employeeName && designation && salary != "") {
let empDetail = {
id: new Date().getTime(),
name: {
employeeIdLocal: employeeId.value,
employeeNameLocal: employeeName.value,
designationLocal: designation.value,
salaryLocal: salary.value,
uniqueEmpId: new Date().getTime(),
},
};
modal.close();
empDetails.push(empDetail);
localStorage.setItem("empDetails", JSON.stringify(empDetails));
modalForm.reset();
createTableRow(empDetail);
}
} else {
tableUpdate(e);
}
});
/////// Create Table Row
function createTableRow(empDetail) {
const tEmployeeMarkup = `
<tr class="fullEmpDetail">
<td id="teId">${empDetail.name.employeeIdLocal}</td>
<td id="teName">${empDetail.name.employeeNameLocal}</td>
<td id="teDesignation">${empDetail.name.designationLocal}</td>
<td id="teSalary">$${empDetail.name.salaryLocal}</td>
<td>
<i class="fas fa-eye"></i>
<i value="Edit" type="button" id="update-row" class="edit-row fas fa-pencil-alt"></i>
<i value="Delete" type="button" class="remove-row fas fa-trash-alt"></i>
</td>
<td id="empDetailId" class="empDetailId">${empDetail.id}</td>
</tr>
`;
empTable.innerHTML += tEmployeeMarkup;
document.getElementById("modal-form").reset();
}
/////// Remove Row
function onDeleteRow(e) {
if (!e.target.classList.contains("remove-row")) {
return;
}
const btn = e.target;
btn.closest("tr").remove();
}
tableContainerContent.addEventListener("click", onDeleteRow);
//////////// Edit Row
tableContainerContent.addEventListener("click", onEditRow);
function onEditRow(e) {
if (e.target.classList.contains("edit-row")) {
modal.showModal();
tr = e.target.parentNode.parentNode;
// console.log(tr);
let tableEmpId = tr.cells[0].textContent;
let tableEmpName = tr.cells[1].textContent;
let tableEmpDesignation = tr.cells[2].textContent;
let tableEmpSalary = tr.cells[3].textContent;
employeeId.value = tableEmpId;
employeeName.value = tableEmpName;
designation.value = tableEmpDesignation;
salary.value = tableEmpSalary;
}
}
///////////////// Update Row
function tableUpdate(e) {
let tableEmpId = document.getElementById("teId");
let tableEmpName = document.getElementById("teName");
let tableEmpDesignation = document.getElementById("teDesignation");
let tableEmpSalary = document.getElementById("teSalary");
tr.cells[0].textContent = employeeId.value;
tr.cells[1].textContent = employeeName.value;
tr.cells[2].textContent = designation.value;
tr.cells[3].textContent = salary.value;
modalForm.reset();
modal.close();
let tableEmpIDs = document.querySelectorAll(".empDetailId");
let empDetails = JSON.parse(localStorage.getItem("empDetails"));
for (let row = 0; row < tableEmpIDs.length; row++) {
for (let i = 0; i < empDetails.length; i++) {
empDetails[i].name.employeeIdLocal = tableEmpId.textContent;
empDetails[i].name.employeeNameLocal = tableEmpName.textContent;
empDetails[i].name.designationLocal = tableEmpDesignation.textContent;
empDetails[i].name.salaryLocal = tableEmpSalary.textContent;
break;
}
}
localStorage.setItem("empDetails", JSON.stringify(empDetails));
}
table
/* th,
td,
tr */
{
border: black solid 1px;
width: 1000px;
text-align: center;
}
table td,
table th {
border: solid 1px black;
width: 200px;
}
table {
border-collapse: collapse;
}
.fas {
margin: 0 10px;
}
.empDetailIdHeader,
.empDetailId {
display: none;
}
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta2/css/all.min.css" integrity="sha512-YWzhKL2whUzgiheMoBFwW8CKV4qpHQAEuvilg9FAn5VJUDwKZZxkJNuGM4XkWuk94WCrrwslk8yWNGmY1EduTA==" crossorigin="anonymous" referrerpolicy="no-referrer"
/>
<link rel="stylesheet" href="./style.css" />
</head>
<body>
<div class="main-container">
<h2>Employee Details</h2>
<button id="addNewEmployee">+ Add New Employee</button>
<div class="table-container-header">
<table>
<tr>
<th>Employee ID</th>
<th>Name</th>
<th>Designation</th>
<th>Salary</th>
<th>Action</th>
<th class="empDetailIdHeader">Local Storage ID</th>
</tr>
</table>
</div>
<div class="table-container-content">
<table id="employeeTable">
</table>
</div>
</div>
<!-- Model Code -->
<div id="#modal-container">
<dialog id="favDialog">
<h2>Enter Employee Details</h2>
<form id="modal-form" method="dialog">
<section>
<p>
<label for="employeeId">Employee ID: </label
><input type="text" id="employeeId" />
</p>
<p>
<label for="employeeName">Name: </label
><input type="text" id="employeeName" />
</p>
<p>
<label for="designation">Designation: </label
><input type="text" id="designation" />
</p>
<p>
<label for="salary">Salary: </label
><input type="text" id="salary" />
</p>
</section>
<menu>
<button id="cancelModal" type="reset">Cancel</button>
<button type="submit" id="submitModal">SUBMIT</button>
</menu>
</form>
</dialog>
</div>
<script src="./script.js"></script>
</body>
</html>
I think you'd be better off just writing the JSON from scratch each time, rather than trying to update it. Something like...
let entries = document.querySelectorAll("table.empDetailsTable tr");
let json = [], props = ['employeeIdLocal', 'employeeNameLocal', 'designationLocal', 'salaryLocal'] // in order that they appear in the table
entries.forEach(row => {
let data = {}
row.querySelectorAll('td').forEach((el, i) => {
data[props[i]] = el.innerText;
})
json.push(data);
})
localStorage.setItem("empDetails", JSON.stringify(data));
I didn't understand your data structure, but hopefully this will suffice or point you in the right direction.
To update LocalStorage values from a dynamically created HTML table
let addNewEmployee = document.getElementById("addNewEmployee");
let modal = document.getElementById("favDialog");
let closeModal = document.getElementById("cancelModal");
let modalForm = document.getElementById("modal-form");
let submitModal = document.getElementById("submitModal");
let tableContainerHeader = document.querySelector(".table-container-header");
let tableContainerContent = document.querySelector(".table-container-content");
let empTable = document.getElementById("employeeTable");
const showModal = addNewEmployee.addEventListener("click", function () {
modal.showModal();
});
closeModal.addEventListener("click", function () {
modal.close();
});
let employeeId = document.getElementById("employeeId");
let employeeName = document.getElementById("employeeName");
let designation = document.getElementById("designation");
let salary = document.getElementById("salary");
let uniqueEmpId = document.getElementById("empDetailId");
let tr = null;
let empDetails = [];
//edit
let editID = "";
let onModalSubmit = modal.addEventListener("submit", function (e) {
e.preventDefault();
if (tr == null && addNewEmployee) {
if (employeeId && employeeName && designation && salary != "") {
let empDetail = {
id: new Date().getTime(),
name: {
employeeIdLocal: employeeId.value,
employeeNameLocal: employeeName.value,
designationLocal: designation.value,
salaryLocal: salary.value,
uniqueEmpId: new Date().getTime(),
},
};
modal.close();
empDetails.push(empDetail);
localStorage.setItem("empDetails", JSON.stringify(empDetails));
modalForm.reset();
createTableRow(empDetail);
}
} else {
tableUpdate(tr);
tr = null;
}
});
/////// Create Table Row
function createTableRow(empDetail) {
const element = document.createElement("tr");
let attr = document.createAttribute("data-id");
attr.value = empDetail.id;
element.setAttributeNode(attr);
element.classList.add("fullEmpDetail");
element.innerHTML = `
<td id="teId">${empDetail.name.employeeIdLocal}</td>
<td id="teName">${empDetail.name.employeeNameLocal}</td>
<td id="teDesignation">${empDetail.name.designationLocal}</td>
<td id="teSalary">$${empDetail.name.salaryLocal}</td>
<td>
<i class="fas fa-eye"></i>
<i value="Edit" type="button" id="update-row" class="edit-row fas fa-pencil-alt"></i>
<i value="Delete" type="button" class="remove-row fas fa-trash-alt"></i>
</td>
`;
empTable.appendChild(element);
document.getElementById("modal-form").reset();
}
/////// Remove Row
function onDeleteRow(e) {
if (!e.target.classList.contains("remove-row")) {
return;
}
const btn = e.target;
btn.closest("tr").remove();
}
tableContainerContent.addEventListener("click", onDeleteRow);
//////////// Edit Row
tableContainerContent.addEventListener("click", onEditRow);
function onEditRow(e) {
if (e.target.classList.contains("edit-row")) {
modal.showModal();
tr = e.target.parentNode.parentNode;
// console.log(tr);
let tableEmpId = tr.cells[0].textContent;
let tableEmpName = tr.cells[1].textContent;
let tableEmpDesignation = tr.cells[2].textContent;
let tableEmpSalary = tr.cells[3].textContent;
employeeId.value = tableEmpId;
employeeName.value = tableEmpName;
designation.value = tableEmpDesignation;
salary.value = tableEmpSalary;
}
}
///////////////// Update Row
function tableUpdate(tr) {
let tableEmpId = document.getElementById("teId");
let tableEmpName = document.getElementById("teName");
let tableEmpDesignation = document.getElementById("teDesignation");
let tableEmpSalary = document.getElementById("teSalary");
console.log(tr);
tr.cells[0].textContent = employeeId.value;
tr.cells[1].textContent = employeeName.value;
tr.cells[2].textContent = designation.value;
tr.cells[3].textContent = salary.value;
editID = tr.dataset.id;
modalForm.reset();
modal.close();
editLocalStorage(editID, tr);
}
///////// Edit Local Storage
function editLocalStorage(editID, tr) {
let empDetails = JSON.parse(localStorage.getItem("empDetails"));
empDetails = empDetails.map((empDetail) => {
if (empDetail.id === parseInt(editID)) {
empDetail.name.employeeIdLocal = tr.cells[0].textContent;
empDetail.name.employeeNameLocal = tr.cells[1].textContent;
empDetail.name.designationLocal = tr.cells[2].textContent;
empDetail.name.salaryLocal = tr.cells[3].textContent;
}
return empDetail;
});
localStorage.setItem("empDetails", JSON.stringify(empDetails));
}

How to get tr element using ParentNode

Use the check boxes to display the tasks that have the active button pressed when you click the "In Progress" check, and the completion button when you click the "Complete" check.
I am trying to implement that only the tasks that are present are displayed.
Currently, when the check box is set to "Complete", "Button only" is hidden.
I have tried the following:
const doneTasks = document.getElementsByTagName('tr');
I tried to get the tr element as above, but it didn't work.
I am thinking that if I get the tr element, the entire task will be hidden, while the button element has been obtained to hide it now.
Please tell me to someone.
{
document.addEventListener('DOMContentLoaded', () => {
const addTaskTrigger = document.getElementsByClassName('addTask-trigger')[0];
const addTaskTarget = document.getElementsByClassName('addTask-target')[0];
const addTaskValue = document.getElementsByClassName('addTask-value')[0];
const radioWork = document.getElementById('radio-work');
const radioDone = document.getElementById('radio-done');
let nextId = 0;
const todos = [];
//Taskとidを作成
const addTask = (task, id, tableItem) => {
const idSpanTd = document.createElement('td');
const taskSpanTd = document.createElement('td');
//タスク追加時にtodosにtodoを追加
//要素内のHTML文章を変更する
idSpanTd.innerText = id;
taskSpanTd.innerText = task;
//生成したテーブル要素をブラウザに表示する
tableItem.append(idSpanTd);
tableItem.append(taskSpanTd);
addTaskTarget.append(tableItem);
};
//Button要素を生成する
const addButton = (tableItem, removeButton, createButton) => {
const createButtonTd = document.createElement('td');
const removeButtonTd = document.createElement('td');
//要素内のHTML文章を変更する
createButton.innerText = '作業中';
removeButton.innerText = '削除';
//生成したテーブル要素をブラウザに表示する
tableItem.append(createButtonTd);
tableItem.append(removeButtonTd);
addTaskTarget.append(tableItem);
//生成したbutton要素を生成する
createButtonTd.append(createButton);
removeButtonTd.append(removeButton);
};
//追加ボタンをクリックした際にtd要素を追加する処理を行う
addTaskTrigger.addEventListener('click', () => {
const task = addTaskValue.value;
const tableItem = document.createElement('tr');
const removeButton = document.createElement('button');
const createButton = document.createElement('button');
addTask(task, nextId++, tableItem);
addButton(tableItem, removeButton, createButton);
addTaskValue.value = '';
// //削除ボタンを押した時にタスクを削除する
const deleteElement = (a) => {
const tableTag = a.target.closest('tr');
if (tableTag) tableTag.remove();
updateId();
}
removeButton.addEventListener('click', deleteElement, false);
//ボタンを押したら作業中、完了中と変わる
createButton.addEventListener('click', (a) => {
if (createButton.textContent === "作業中") {
createButton.textContent = "完了";
const doneParent = a.target.parentNode;
doneParent.className = 'workDone';/*完了class*/
} else {
createButton.textContent = "作業中";
const workParent = a.target.parentNode;
workParent.className = 'work';/*作業中class*/
}
});
})
//todoの状態を管理
const todo = [{task: 'taskSpanTd',status: '作業中'},{task: 'taskSpanTd',status: '完了'}]
todos.push(todo);
/*ラジオボタン作業中を押下時の処理*/
radioDone.addEventListener('click', function () {
let workTasks = document.getElementsByClassName('work');
workTasks = Array.from(tr);
if (radioWork.checked.tr=== true) {
workTasks.forEach(function (workTasks) {
workTasks.style.display = "";
})
} else {
workTasks.forEach(function (workTasks) {
workTasks.style.display = "none";
})
}
})
// ラジオボタン完了押下時処理
radioWork.addEventListener('click', function () {
let doneTasks = document.getElementsByClassName('workDone');
doneTasks = Array.from(tr);
if (radioDone.checked.tr === true) {
doneTasks.forEach(function (doneTasks) {
doneTasks.style.display = "";
})
} else {
doneTasks.forEach(function (doneTasks) {
doneTasks.style.display = "none";
})
}
})
// 連番 再振り直し
const updateId = () => {
const tbody = document.getElementsByTagName("tbody")[0];
const taskList = tbody.getElementsByTagName('tr');
nextId = 0;
Array.from(taskList, tr => {
tr.getElementsByTagName('td')[0].textContent = nextId;
nextId++
});
}
});
}
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="css/style.css">
<title>Todoリスト</title>
</head>
<body>
<h1>Todoリスト</h1>
<p>
<input type="radio" name="task" value="1" checked ="checked">全て
<input type="radio" id="radio-work" name="task" value="2">作業中
<input type="radio" id="radio-done" name="task" value="3">完了
</p>
<p></p>
<table>
<thead>
<th>ID</th>
<th>コメント</th>
<th>状態</th>
<th></th>
</thead>
<tbody class="addTask-target" id="tbody"></tbody>
</table>
<h2>新規タスクの追加</h2>
<input class="addTask-value" type="text" />
<button class="addTask-trigger" type="button">追加</button>
<script src="js/main.js"></script>
</body>
</html>
It's not good idea to select the tr tag by using it parent for example you can select child elements of div like
var div = document.getElementById('parent');
div.firstElementChild.style.background = 'red';
div.lastElementChild.style.background = 'blue';
#parent {
width: 100px;
height: 100px;
position: relative;
}
.child {
width: 100%;
height: 50%;
}
<div id="parent">
<div class="child"></div>
<div class="child"></div>
</div>
but this can't be done on table if you you do it you will not point only one tr it will be applied on all tr like the following example
table = document.getElementsByTagName('table')[0];
table.firstElementChild.style.background = 'grey';
table.lastElementChild.style.background = 'green';
<table border="1px" cellpadding="5px">
<tr>
<th>Names</th>
</tr>
<tr>
<td>Eric</td>
</tr>
<tr>
<td>Ivan</td>
</tr>
</table>
so better select all table row in table and loop on the to get one by one like
tr = document.getElementsByTagName('tr');
for (var i = 0; i < tr.length; i++) {
if (i == 0) {
tr[i].style.background = 'green';
} else if (i == 1) {
tr[i].style.background = 'grey';
} else {
tr[i].style.background = 'cyan';
}
}
<table border="1px" cellpadding="5px">
<tr>
<th>Names</th>
</tr>
<tr>
<td>Eric</td>
</tr>
<tr>
<td>Ivan</td>
</tr>
</table>

How to query an AJAX imported table (instead of a local table) using javascript

Currently, I have a script that searches column 1 of a locally-stored table, and returns the result from column 2 from the same row. Based on that result, it logs something to the console.
Here it is action. It searches the table for "dragon" in column 1, returns "2" from Column 2, then the script logs "The result is two." to the console.
var username = 'dragon'
const searchDataSetByKey = (dataSet, key) => {
return dataSet.find((data) => data[0] === key)
}
document.addEventListener('DOMContentLoaded', () => {
var tableToArray = Array
.from(document.querySelectorAll('tr'))
.reduce((_tableToArray, tableRow, tableRowIndex) => {
if(tableRowIndex !== 0) {
var tableData = tableRow.querySelectorAll('td')
var key = tableData.item(0).innerText
var value = tableData.item(1).innerText
_tableToArray.push([key, value])
}
return _tableToArray
}, [])
var searchString = searchDataSetByKey(tableToArray,username).toString()
var oneSearch = searchString.indexOf("1")
var twoSearch = searchString.indexOf("2")
var threeSearch = searchString.indexOf("3")
if (oneSearch >= 0) {
console.log('The result is one!');}
else if (twoSearch >= 0) {
console.log('This result is two.');}
else if (threeSearch >= 0) {
console.log('The answer is three! :)');}
})
<html>
<script src="script.js"></script>
<body>
<table>
<tr>
<th>Username</th>
<th>1/2/3</th>
</tr>
<tr>
<td>wisp</td>
<td>1</td>
</tr>
<tr>
<td>husky</td>
<td>2</td>
</tr>
<tr>
<td>dragon</td>
<td>2</td>
</tr>
<tr>
<td>woop</td>
<td>3</td>
</tr>
<tr>
<td>e6</td>
<td>1</td>
</tr>
</table>
</body>
</html>
This is great for locally-stored tables. The issue is, I'd like to get the same result from a Google Sheet. I've found a way to store the info from a Google Sheet into a HTML table using AJAX. The code for this can be seen here:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
var spData = null;
function doData(json) {
spData = json.feed.entry;
}
function drawCell(tr, val) {
var td = $("<td/>");
tr.append(td);
td.append(val);
return td;
}
function drawRow(table, rowData) {
if (rowData == null) return null;
if (rowData.length == 0) return null;
var tr = $("<tr/>");
table.append(tr);
for(var c=0; c<rowData.length; c++) {
drawCell(tr, rowData[c]);
}
return tr;
}
function drawTable(parent) {
var table = $("<table/>");
parent.append(table);
return table;
}
function readData(parent) {
var data = spData;
var table = drawTable(parent);
var rowData = [];
for(var r=0; r<data.length; r++) {
var cell = data[r]["gs$cell"];
var val = cell["$t"];
if (cell.col == 1) {
drawRow(table, rowData);
rowData = [];
}
rowData.push(val);
}
drawRow(table, rowData);
}
$(document).ready(function(){
readData($("#data"));
});
</script>
<script src="https://spreadsheets.google.com/feeds/cells/1P9DhWOHcl14Y7-P5wCxTm-sUceckGquPoOobO75XhvM/1/public/values?alt=json-in-script&callback=doData"></script>
<style type="text/css" media="print">
form {display: none;}
</style>
</head>
<body>
<div id="data"/>
</body>
</html>
I was wondering if there was any way of achieving what was done in the local HTML table, with this AJAX imported HTML table?
Thanks!
It's exactly the same work that you need to do, albeit at a different time - i.e in response to a different event. Do it straight after you've loaded the table, instead of straight after you've received the DOMContentLoaded event from the document. Here's an alternate way to go looking.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
var spData = null;
function doData(json) {
spData = json.feed.entry;
}
function drawCell(tr, val) {
var td = $("<td/>");
tr.append(td);
td.append(val);
return td;
}
function drawRow(table, rowData) {
if (rowData == null) return null;
if (rowData.length == 0) return null;
var tr = $("<tr/>");
table.append(tr);
for(var c=0; c<rowData.length; c++) {
drawCell(tr, rowData[c]);
}
return tr;
}
function drawTable(parent) {
var table = $("<table/>");
parent.append(table);
return table;
}
function readData(parent) {
var data = spData;
var table = drawTable(parent);
var rowData = [];
for(var r=0; r<data.length; r++) {
var cell = data[r]["gs$cell"];
var val = cell["$t"];
if (cell.col == 1) {
drawRow(table, rowData);
rowData = [];
}
rowData.push(val);
}
drawRow(table, rowData);
}
$(document).ready(function(){
readData($("#data"));
searchTable( 'dragon', document.querySelector('table') );
});
function searchTable(searchStr, target)
{
let rows = Array.from( target.querySelectorAll('tr') );
rows.forEach( (row,idx,col) => {
let firstCell = row.querySelector('td').textContent;
if (firstCell == searchStr)
{
let cell2 = row.querySelectorAll('td')[1].textContent;
console.log(`${searchStr} found in row ${idx}`);
console.log(`col 2 of row #${idx} is: ${cell2}`);
}
}
);
}
</script>
<script src="https://spreadsheets.google.com/feeds/cells/1P9DhWOHcl14Y7-P5wCxTm-sUceckGquPoOobO75XhvM/1/public/values?alt=json-in-script&callback=doData"></script>
<style type="text/css" media="print">
form {display: none;}
</style>
</head>
<body>
<div id="data"/>
</body>
</html>

Updating row ID when swapping HTML table rows

I've been messing with manipulating HTML tables for the past few weeks and I've come across a problem I am not sure how to fix. So the collection of rows for a table can be iterated over like an array, but if you've switched out the rows a lot, won't the IDs be mixed and doesn't the browser rely on the IDs as the way to iterate over the row objects? I'm running into a problem (probably due to a lack of understanding) where the rows eventually stop moving or one row gets duplicated on top of another. Should I somehow be updating the row's ID each time it is moved? Here is my source so far for this function.
function swap(rOne, rTwo, tblID) {
tblID.rows[rOne].setAttribute('style', 'background-color:#FFFFFF');
var tBody = tblID.children[0];
var rowOne;
var rowTwo;
if (rOne > rTwo) {
rowOne = rOne;
rowTwo = rTwo;
}
else {
rowOne = rTwo;
rowTwo = rOne;
}
var swapTempOne = tblID.rows[rowOne].cloneNode(true);
var swapTempTwo = tblID.rows[rowTwo].cloneNode(true);
hiddenTable.appendChild(swapTempOne);
hiddenTable.appendChild(swapTempTwo);
tblID.deleteRow(rowOne);
var rowOneInsert = tblID.insertRow(rowOne);
var rowOneCellZero = rowOneInsert.insertCell(0);
var rowOneCellOne = rowOneInsert.insertCell(1);
var rowOneCellTwo = rowOneInsert.insertCell(2);
var rowOneCellThree = rowOneInsert.insertCell(3);
rowOneCellZero.innerHTML = hiddenTable.rows[2].cells[0].innerHTML;
rowOneCellOne.innerHTML = hiddenTable.rows[2].cells[1].innerHTML;
rowOneCellTwo.innerHTML = hiddenTable.rows[2].cells[2].innerHTML;
rowOneCellThree.innerHTML = hiddenTable.rows[2].cells[3].innerHTML;
tblID.deleteRow(rowTwo);
var rowTwoInsert = tblID.insertRow(rowTwo);
var rowTwoCellZero = rowTwoInsert.insertCell(0);
var rowTwoCellOne = rowTwoInsert.insertCell(1);
var rowTwoCellTwo = rowTwoInsert.insertCell(2);
var rowTwoCellThree = rowTwoInsert.insertCell(3);
rowTwoCellZero.innerHTML = hiddenTable.rows[1].cells[0].innerHTML;
rowTwoCellOne.innerHTML = hiddenTable.rows[1].cells[1].innerHTML;
rowTwoCellTwo.innerHTML = hiddenTable.rows[1].cells[2].innerHTML;
rowTwoCellThree.innerHTML = hiddenTable.rows[1].cells[3].innerHTML;
tblID.rows[rowOne].setAttribute('onclick', 'chkThis(event, this)');
tblID.rows[rowTwo].setAttribute('onclick', 'chkThis(event, this)');
for (iHiddenDelete = 2; iHiddenDelete >= 1; iHiddenDelete--) {
hiddenTable.deleteRow(iHiddenDelete);
}
}
EDIT: Adding HTML for page and the function for moving between tables which I suspect is causing the issue.
<body>
<form>
<input value="0" type="text" id="cubesum" size="5"/>
<input value="0" type="text" id="wgtsum" size="5"/>
</form>
<form>
<table id="tblSource">
<thead>
<tr>
<th> </th>
<th>Order</th>
<th>Cube</th>
<th>Weight</th>
<th>Move</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<button type="button" onclick="move('tblSource','tblTarget')" style="width: 58px">To Trucks (Down)</button>
<button type="button" onclick="move('tblTarget', 'tblSource')" style="width: 58px">To Orders (Up)</button>
</form>
<form>
<table id="tblTarget">
<thead>
<tr>
<th> </th>
<th>Order</th>
<th>Cube</th>
<th>Weight</th>
<th>Move</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</form>
<table id="hiddenTable" style="display: none"> <!--this table is hidden! -->
<thead>
<tr>
<th> </th>
<th>Order</th>
<th>Cube</th>
<th>Weight</th>
<th>Move</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</body>
</html>
FUNCTION STARTS HERE
function move(from, to) {
var frTbl = document.getElementById(from);
var toTbl = document.getElementById(to);
chkArray.length = 0;
cbsMove = frTbl.getElementsByTagName('input');
for (var oChk = 0; oChk < cbsMove.length; oChk++) {
if (cbsMove[oChk].type == 'checkbox') {
if (cbsMove[oChk].checked == true) {
var prntRow = cbsMove[oChk].parentNode.parentNode;
var prntRowIdx = prntRow.rowIndex;
chkArray.push(prntRowIdx);
cbsMove[oChk].checked = false;
}
}
}
for (iMove = chkArray.length -1; iMove >= 0; iMove--) {
var num = chkArray[iMove];
var row = frTbl.rows[num];
var cln = row.cloneNode(true);
toTbl.appendChild(cln);
frTbl.deleteRow(num);
}
sum();
}
So it turns out that my row cloning for moving between tables was causing malformed HTML where the rows would not longer be inside the table body tags. In addition, not trusting the browser to keep track of the button IDs and using the button IDs to setAttributes to the button also caused button ID overlap eventually. So, I got rid of the node cloning and did the row moving between tables the manual way and used innerHTML to add the function call inside the buttons. Upon further reflection, I've come to learn that some people actually make functions that handle ALL button clicks without calling them inside the button and route them to the proper function depending on the ID or other factors such as parent nodes of the button. Perhaps that is best. The main trick here is to STICK TO ONE METHOD. I was all over the place in how I manipulated the tables and it broke things. Here is the working source for those looking to do similar things.
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<style type="text/css">
#selectSource {
width: 320px;
}
#selectTarget {
width: 320px;
}
table, th, td
{
border: 1px solid black;
}
</style>
<title>Loader</title>
<script>
var chkArray = [];
var data = [];
var tmpArray = [];
var iChk = 0;
var swap;
window.onload = function () {
var load = document.getElementById('selectSource')
loadFromAJAX();
}
function loadFromAJAX()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var rawData = xmlhttp.responseText;
data = JSON.parse(rawData);
for (iData = 0; iData < data.length; iData++) {
newRow = document.getElementById('tblSource').insertRow(iData + 1);
var dn = "dn" + (iData + 1);
var up = "up" + (iData + 1);
cel0 = newRow.insertCell(0);
cel1 = newRow.insertCell(1);
cel2 = newRow.insertCell(2);
cel3 = newRow.insertCell(3);
cel4 = newRow.insertCell(4);
cel0.innerHTML = "<input type='checkbox' name='chkbox'>";
cel1.innerHTML = data[iData].num;
cel2.innerHTML = data[iData].cube;
cel3.innerHTML = data[iData].wgt;
cel4.innerHTML = "<button type='button' onclick=moveUp(this)>up</button><button type='button' onclick=moveDn(this)>down</button>";
}
}
}
xmlhttp.open("POST","http://192.168.3.2/cgi-bin/rims50.cgi/json.p",true);
xmlhttp.send();
}
function moveUp(mvThisRow) {
var mvThisRowRow = mvThisRow.parentNode.parentNode;
var mvThisRowTbl = mvThisRowRow.parentNode.parentNode;
var mvThisRowIndex = mvThisRowRow.rowIndex;
var mvThisRowTblLngth = mvThisRowTbl.rows.length;
var mvFrRow = mvThisRowTbl.rows[mvThisRowIndex];
var mvToRow = mvThisRowIndex - 1;
var mvThisDn = "dn" + (mvToRow) + mvThisRowTbl;
var mvThisUp = "up" + (mvToRow) + mvThisRowTbl;
if (mvThisRowIndex - 1 !== 0) {
moveToRow = mvThisRowTbl.insertRow(mvToRow);
mvRowCel0 = moveToRow.insertCell(0);
mvRowCel1 = moveToRow.insertCell(1);
mvRowCel2 = moveToRow.insertCell(2);
mvRowCel3 = moveToRow.insertCell(3);
mvRowCel4 = moveToRow.insertCell(4);
mvRowCel0.innerHTML = "<input type='checkbox' name='chkbox'>";
mvRowCel1.innerHTML = mvFrRow.cells[1].innerHTML;
mvRowCel2.innerHTML = mvFrRow.cells[2].innerHTML;
mvRowCel3.innerHTML = mvFrRow.cells[3].innerHTML;
mvRowCel4.innerHTML = "<button type='button' onclick=moveUp(this)>up</button><button type='button' onclick=moveDn(this)>down</button>";
mvThisRowTbl.deleteRow(mvThisRowIndex +1);
}
else {
alert("You can't move the top row 'up' try moving it 'down'.");
}
}
function moveDn(mvThisRow) {
var mvThisRowRow = mvThisRow.parentNode.parentNode;
var mvThisRowTbl = mvThisRowRow.parentNode.parentNode;
var mvThisRowTblLngth = mvThisRowTbl.rows.length;
var mvThisRowIndex = mvThisRowRow.rowIndex;
if (mvThisRowIndex + 1 !== mvThisRowTblLngth) {
var mvFrRow = mvThisRowTbl.rows[mvThisRowIndex];
var mvToRow = mvThisRowIndex + 2;
var moveToRow = mvThisRowTbl.insertRow(mvToRow);
var dn = "dn" + (mvToRow) + mvThisRowTbl;
var up = "up" + (mvToRow) + mvThisRowTbl;
mvRowCel0 = moveToRow.insertCell(0);
mvRowCel1 = moveToRow.insertCell(1);
mvRowCel2 = moveToRow.insertCell(2);
mvRowCel3 = moveToRow.insertCell(3);
mvRowCel4 = moveToRow.insertCell(4);
mvRowCel0.innerHTML = "<input type='checkbox' name='chkbox'>";
mvRowCel1.innerHTML = mvFrRow.cells[1].innerHTML;
mvRowCel2.innerHTML = mvFrRow.cells[2].innerHTML;
mvRowCel3.innerHTML = mvFrRow.cells[3].innerHTML;
mvRowCel4.innerHTML = "<button type='button' onclick=moveUp(this)>up</button><button type='button' onclick=moveDn(this)>down</button>";
mvThisRowTbl.deleteRow(mvThisRowIndex);
}
else {
alert("You can't move the bottom row 'down' try moving it 'up'.");
}
}
function sum() {
var trgTbl = document.getElementById('tblTarget');
var tblLength = trgTbl.rows.length;
var sumAddCube = 0;
var sumAddWgt = 0;
document.getElementById("cubesum").setAttribute("value", sumAddCube);
document.getElementById("wgtsum").setAttribute("value", sumAddWgt);
for (iSum = 1; iSum < tblLength; iSum++) {
celCubeNum = trgTbl.rows[iSum].cells[2].innerHTML;
celWgtNum = trgTbl.rows[iSum].cells[3].innerHTML;
sumAddCube = parseInt(sumAddCube) + parseInt(celCubeNum);
sumAddWgt = parseInt(sumAddWgt) + parseInt(celWgtNum);
}
document.getElementById("cubesum").setAttribute("value", sumAddCube);
document.getElementById("wgtsum").setAttribute("value", sumAddWgt);
}
function move(from, to) {
var frTbl = document.getElementById(from);
var toTbl = document.getElementById(to);
chkArray.length = 0;
cbsMove = frTbl.getElementsByTagName('input');
for (var oChk = 0; oChk < cbsMove.length; oChk++) {
if (cbsMove[oChk].type == 'checkbox') {
if (cbsMove[oChk].checked == true) {
var prntRow = cbsMove[oChk].parentNode.parentNode;
var prntRowIdx = prntRow.rowIndex;
chkArray.push(prntRowIdx);
cbsMove[oChk].checked = false;
}
}
}
for (iMove = chkArray.length -1; iMove >= 0; iMove--) {
var num = chkArray[iMove];
var row = frTbl.rows[num];
var toRow = toTbl.rows.length
moveRow = toTbl.insertRow(toRow);
var dn = "dn" + (toRow) + toTbl;
var up = "up" + (toRow) + toTbl;
mvCel0 = moveRow.insertCell(0);
mvCel1 = moveRow.insertCell(1);
mvCel2 = moveRow.insertCell(2);
mvCel3 = moveRow.insertCell(3);
mvCel4 = moveRow.insertCell(4);
mvCel0.innerHTML = "<input type='checkbox' name='chkbox'>";
mvCel1.innerHTML = row.cells[1].innerHTML;
mvCel2.innerHTML = row.cells[2].innerHTML;
mvCel3.innerHTML = row.cells[3].innerHTML;
mvCel4.innerHTML = "<button type='button' onclick=moveUp(this)>up</button><button type='button' onclick=moveDn(this)>down</button>";
frTbl.deleteRow(num);
}
sum();
}
</script>
</head>
<body>
<form>
<input value="0" type="text" id="cubesum" size="5"/>
<input value="0" type="text" id="wgtsum" size="5"/>
</form>
<form>
<table id="tblSource">
<thead>
<tr>
<th> </th>
<th>Order</th>
<th>Cube</th>
<th>Weight</th>
<th>Move</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<button type="button" onclick="move('tblSource','tblTarget')" style="width: 58px">To Trucks (Down)</button>
<button type="button" onclick="move('tblTarget', 'tblSource')" style="width: 58px">To Orders (Up)</button>
</form>
<form>
<table id="tblTarget">
<thead>
<tr>
<th> </th>
<th>Order</th>
<th>Cube</th>
<th>Weight</th>
<th>Move</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</form>
<table id="hiddenTable" style="display: none"> <!--this table is hidden! -->
<thead>
<tr>
<th> </th>
<th>Order</th>
<th>Cube</th>
<th>Weight</th>
<th>Move</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</body>
</html>

Javascript Dynamic Table

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>

Categories

Resources