I'm trying to create a table in HTML using javascript. It has an add button that add's new rows and a delete button that removes rows. It looks like this :
the numbers are the ids
<table id = "table1" border = 2>
<tr>
<td> <img id="add" src="images/add_over.png" onclick=help() /> </td>
</tr>
</table>
Basically I'm trying to delete the whole table and recreate it with one row less.
var array1 = new Array();
function help() {
addRow();
push();
}
function addRow() {
var tableId= "table1";
var number= array1.length;
var newRow = document.getElementById(tableId).insertRow(number+ 1);
var newData = document.createElement("td");
var newDiv= document.createElement("div");
newDiv.innerHTML = array1.length;
newData.appendChild(newDiv);
var newCellDeleteButton = document.createElement("td");
var deleteButtonImg = document.createElement('img');
deleteButtonImg.id = number;
deleteButtonImg.border = '0';
deleteButtonImg.src = "images/delete_up.png";
deleteButtonImg.onmouseover = function() {
this.src = 'images/delete_over.png';
};
deleteButtonImg.onmouseout = function() {
this.src = 'images/delete_up.png';
};
deleteButtonImg.onclick = function() {
deleteRow(number);
};
newCellDeleteButton.appendChild(deleteButtonImg);
newRow.appendChild(newRow);
newRow.appendChild(newCellDeleteButton);
}
function deleteRow(rowID) {
var tempHelpRow = array1.length;
pop(rowID);
for (var i = 1; i <= tempHelpRow ; i++) {
document.getElementById("table1").deleteRow(1);
}
for (var i = 0; i <= array1.length; i++) {
addRow();
}
}
function pop(ID) {
array1.pop(ID);
}
function push() {
var test = new objectt();
array1.push(test);
}
function objectt() {
}
the problem is, that if i try to delete one row it deletes everything.
Related
I don't know the problem with my code, I'm trying to make an editable cell when you click edit it edits the cell plus instead of the edit and delete buttons there should appear a save button that works, (I have a problem with that it doesn't work), here is my html code of my table:
function deleteButtons(btns, tdBtns) {
for (let index = 0; index < btns.length; index += index) {
tdBtns.removeChild(btns[index]);
}
}
function createButtons(bool, td) {
if (bool) {
var Edit = document.createElement('input');
Edit.type = "button";
Edit.value = "Edit";
Edit.setAttribute('onclick', 'Edit(this)');
td.appendChild(Edit);
var Delete = document.createElement('input');
Delete.type = "button";
Delete.setAttribute('onclick', 'Delete(this)');
Delete.value = "Delete";
td.appendChild(Delete);
} else {
var Save = document.createElement('input');
Save.type = "button";
Save.value = "Save";
Save.setAttribute('onclick', 'Save(this)');
td.appendChild(Save);
}
}
function Add() {
var p1 = document.getElementById("txt").value;
const row1 = document.getElementById("row1");
var table = document.getElementById("MyTable");
//insert row beginning or end
var element = document.createElement("tr");
var table = document.getElementById("MyTable");
table.appendChild(element);
if (document.getElementById('input1').checked) {
table.insertBefore(element, table.firstElementChild);
} else if (document.getElementById('input2').checked) {
table.lastElementChild.after(element);
}
var case1 = document.createElement("td");
case1.innerHTML = p1;
element.appendChild(case1);
var case2 = document.createElement("td");
element.appendChild(case2);
createButtons(true, case2);
}
//delete:
function Delete(element) {
element.parentNode.parentNode.parentNode.removeChild(element.parentNode.parentNode);
}
//Edit:
function Edit(element) {
const row = element.parentNode.parentNode;
const tdList = row.children;
for (let index = 0; index < tdList.length - 1; index++) {
const element = tdList[index];
var str = element.childNodes[0].nodeValue;
var input = document.createElement("input");
input.type = "text";
input.id = "edit" + (index + 1).toString();
input.value = str;
element.removeChild(element.childNodes[0]);
element.appendChild(input);
}
const tdBtns = tdList[1];
const btns = tdBtns.children;
deleteButtons(btns, tdBtns);
createButtons(false, tdBtns);
}
function Save(element) {
const row = element.parentNode.parentNode;
const tdList = row.children;
/* const edit = [
['edit1'],
['edit2']
]; */
const edit = [];
for (let index = 0; index <= 1; index++) {
edit[index] = document.getElementById("edit" + (index + 1).toString()).value;
if (edit[index] == "") {
alert("You must not keep textboxes empty");
var empty = true;
}
}
if (!empty) {
for (let index = 0; index < tdList.length - 1; index++) {
tdList[index].removeChild(tdList[index].children[0]);
var text = document.createTextNode(edit[index]);
tdList[index].appendChild(text);
}
const tdBtns = tdList[1];
const btns = tdBtns.children;
deleteButtons(btns, tdBtns);
createButtons(true, tdBtns);
}
}
<h1>Table</h1>
<div id="principal">
<div id="cntr"><input type="text" id="txt" placeholder="Element to add.">
<input type="button" value="Add" onclick="Add()"><br><br></div>
<form id="frm">
Add :
<input type="radio" name="test" id="input1"> at the beginning
<input type="radio" name="test" id="input2"> at the end
</form><br>
<table id="MyTable">
<tbody>
<tr id="row1">
<td id="name_row1">Element 1 </td>
<td>
<input type="button" id="edit_button1" value="Edit" onclick="Edit(this)">
<input type="button" value="Supprimer" onclick="Delete(this)">
</td>
</tr>
</table>
</div>
I would appreciate any help
The console is your friend. When you try to edit a td, it clearly warns you that you're trying to access "value" from a null object. It's to do with this part of the Save() function:
for (let index = 0; index <= 1; index++) {
edit[index] = document.getElementById("edit" + (index + 1).toString()).value;
The big issue here is where does index <= 1 come from? In theory you're looping through the tds in the row, right? Right now there's only one, and I see no way to add more for now.
So it tries to access the value property of an element with id "edit2" in the second iteration of the for loop. "edit2" doesn't exist, hence the error.
Funny thing is that the solution is already in your code. In your Edit() function you loop through the number of row children, with index < tdList.length - 1. Well, simply use that in your Save() function and it works fine!
You'll see it working in the snippet:
function deleteButtons(btns, tdBtns) {
for (let index = 0; index < btns.length; index += index) {
tdBtns.removeChild(btns[index]);
}
}
function createButtons(bool, td) {
if (bool) {
var Edit = document.createElement('input');
Edit.type = "button";
Edit.value = "Edit";
Edit.setAttribute('onclick', 'Edit(this)');
td.appendChild(Edit);
var Delete = document.createElement('input');
Delete.type = "button";
Delete.setAttribute('onclick', 'Delete(this)');
Delete.value = "Delete";
td.appendChild(Delete);
} else {
var Save = document.createElement('input');
Save.type = "button";
Save.value = "Save";
Save.setAttribute('onclick', 'Save(this)');
td.appendChild(Save);
}
}
function Add() {
var p1 = document.getElementById("txt").value;
const row1 = document.getElementById("row1");
var table = document.getElementById("MyTable");
//insert row beginning or end
var element = document.createElement("tr");
var table = document.getElementById("MyTable");
table.appendChild(element);
if (document.getElementById('input1').checked) {
table.insertBefore(element, table.firstElementChild);
} else if (document.getElementById('input2').checked) {
table.lastElementChild.after(element);
}
var case1 = document.createElement("td");
case1.innerHTML = p1;
element.appendChild(case1);
var case2 = document.createElement("td");
element.appendChild(case2);
createButtons(true, case2);
}
//delete:
function Delete(element) {
element.parentNode.parentNode.parentNode.removeChild(element.parentNode.parentNode);
}
//Edit:
function Edit(element) {
const row = element.parentNode.parentNode;
const tdList = row.children;
for (let index = 0; index < tdList.length - 1; index++) {
const element = tdList[index];
var str = element.childNodes[0].nodeValue;
var input = document.createElement("input");
input.type = "text";
input.id = "edit" + (index + 1).toString();
input.value = str;
element.removeChild(element.childNodes[0]);
element.appendChild(input);
}
const tdBtns = tdList[1];
const btns = tdBtns.children;
deleteButtons(btns, tdBtns);
createButtons(false, tdBtns);
}
function Save(element) {
const row = element.parentNode.parentNode;
const tdList = row.children;
/* const edit = [
['edit1'],
['edit2']
]; */
const edit = [];
for (let index = 0; index < tdList.length -1; index++) {
if (!document.getElementById("edit" + (index + 1).toString())) {
console.warn('no element with id ' + "edit" + (index + 1).toString());
continue;
}
edit[index] = document.getElementById("edit" + (index + 1).toString()).value;
if (edit[index] == "") {
alert("You must not keep textboxes empty");
var empty = true;
}
}
if (!empty) {
for (let index = 0; index < tdList.length - 1; index++) {
tdList[index].removeChild(tdList[index].children[0]);
var text = document.createTextNode(edit[index]);
tdList[index].appendChild(text);
}
const tdBtns = tdList[1];
const btns = tdBtns.children;
deleteButtons(btns, tdBtns);
createButtons(true, tdBtns);
}
}
<h1>Table</h1>
<div id="principal">
<div id="cntr"><input type="text" id="txt" placeholder="Element to add.">
<input type="button" value="Add" onclick="Add()"><br><br></div>
<form id="frm">
Add :
<input type="radio" name="test" id="input1"> at the beginning
<input type="radio" name="test" id="input2"> at the end
</form><br>
<table id="MyTable">
<tbody>
<tr id="row1">
<td id="name_row1">Element 1 </td>
<td>
<input type="button" id="edit_button1" value="Edit" onclick="Edit(this)">
<input type="button" value="Supprimer" onclick="Delete(this)">
</td>
</tr>
</table>
</div>
This is my dynamic table
After clicking button it generate table based on input.
$(function () {
$("#btnGenerate").click(function () {
var textarea = document.getElementById("inglist");
var lines = textarea.value.replace(/\r\n/g,"\n").split(/:|,|\n/);
var lines2 = textarea.value.split(/(\d+(?:\.\d+)?)/);
lines.forEach((o, i) => o.id = i + 1);
var array1=new Array();
for (var i = 1; i < lines .length; i++) {
array1.push(lines [i].replace(/\[.*?\]/g, ''));}
const results = [];
array1.forEach(line => {
const filtered = line.split(/([\s\w]+)\s(\d+(?:\.\d+)?)(%?)\s*(\[\d\])?/g).filter(Boolean);
results.push(filtered);
});
var build = new Array();
build.push(["ING name:", "Total:","unit", "Count it?:","x2?"]);
var table1 = $("<table />");
for(var i=0;i<results.length;i++){
build.push(results[i]);
}
var countColumns = build[0].length;
console.log(countColumns);
var tables = $("<table /><class='form-control input-md'>");
//Add the header row.
var rows = $(tables[0].insertRow(-1));
for (var i = 0; i < countColumns; i++) {
var headerCell = $("<th /><class='form-control input-md'>");
headerCell.html(build[0][i]);
rows.append(headerCell);
}
//Add the data rows.
for (var i = 1; i < build.length; i++) {
row = $(tables[0].insertRow(-1));
for (var j = 0; j < countColumns; j++) {
var cell = $('<td><input type="checkbox"/>');
cell.html(build[i][j]);
row.append(cell);
}
}
var dvTable1 = $("#dvTable1");
dvTable1.html("");
dvTable1.append(tables);
});
How i can assign dynamic ID to every checkbox ?
And then how to filter only rows where is tick checkbox in 3rd column ( count in?: )
I am working on an app development which will read through my mailbox and list all the unread e-mails in a HTML table on my web-app upon click of a button. Below is the code which I have made while researching through google which solves for the purpose.
<!DOCTYPE html>
<html>
<body>
<button onclick="groupFunction()">Click me</button>
<table id="tblContents">
<tr onclick="tableClickTest()">
<th>Sender</th>
<th>Sent_Date</th>
<th>Received_By</th>
<th>Received_Date</th>
<th>Subject</th>
</tr>
</table>
<script>
function RowSelection()
{
var table = document.getElementById("tblContents");
if (table != null) {
for (var i = 0; i < table.rows.length; i++) {
for (var j = 0; j < table.rows[i].cells.length; j++)
table.rows[i].cells[j].onclick = function () {
tableText(this);
};
}
}
}
function tableText(tableCell) {
alert(tableCell.innerHTML);
}
function PopulateTable()
{
var objOutlook = new ActiveXObject("Outlook.Application");
var session = objOutlook.Session;
//alert(session.Folders.Count)
for(var folderCount = 1;folderCount <= session.Folders.Count; folderCount++)
{
var folder = session.Folders.Item(folderCount);
//alert(folder.Name)
if(folder.Name.indexOf("Premanshu.Basak#genpact.com")>=0)
{
for(var subFolCount = 1; subFolCount <= folder.Folders.Count; subFolCount++)
{
var sampleFolder = folder.Folders.Item(subFolCount);
//alert(sampleFolder.Name)
if(sampleFolder.Name.indexOf("test1")>=0)
{
for(var itmCount = 1; itmCount <= sampleFolder.Items.Count; itmCount++)
{
var itm = sampleFolder.Items.Item(itmCount);
if(!itm.UnRead)
continue;
var sentBy = itm.SenderName;
var sentDate = itm.SentOn;
var receivedBy = itm.ReceivedByName;
var receivedDate = itm.ReceivedTime;
var subject = itm.ConversationTopic;
// var contents = itm.Body;
var tbl = document.getElementById("tblContents");
if(tbl)
{
var tr = tbl.insertRow(tbl.rows.length);
// tr.onclick(tableClickTest())
if(tbl.rows.length%2 != 0)
tr.className = "alt";
var tdsentBy = tr.insertCell(0);
var tdsentDate = tr.insertCell(1);
var tdreceivedBy = tr.insertCell(2);
var tdreceivedDate = tr.insertCell(3);
var tdsubject = tr.insertCell(4);
// var tdcontents = tr.insertCell(5);
tdsentBy.innerHTML = sentBy;
tdsentDate.innerHTML = sentDate;
tdreceivedBy.innerHTML = receivedBy;
tdreceivedDate.innerHTML = receivedDate;
tdsubject.innerHTML = subject;
// tdcontents.innerHTML = contents;
}
//itm.UnRead = false;
}
break;
}
}
break;
}
}
return;
}
function groupFunction()
{
PopulateTable()
RowSelection()
}
</script>
</body>
</html>
The thing that I am now looking for and is unable to do is how do I add a checkbox in the first column in each row. Also upon checking this checkbox the entire row should get highlighted so that I can perform specific task on all the selected items.
As far as I have understood your code, your first column's data is being set as:
tdsentBy.innerHTML = sentBy;
So in the same line, you can add textbox as a string as:
var cbox = "<div class='select-box'>
<input type='checkbox' name='selectBox' class='select-row'>
</div?>"
tdsentBy.innerHTML = cbox + sentBy;
In this way, a checkbox will always be available in first column of every row.
Now in RowSelection function, to bind event you can do something like:
var checkBox = table.rows[i].cells[j].querySelector(".select-row");
checkBox.addEventListener("click",function(evt){
});
I have a table in my popup and I save the values entered by a user to localStorage. Here are the snippets.
popup.html
<table id="main_table">
</table>
<script src="popup.js"></script>
popup.js
function create_row() {
localStorage["last_session"] = true;
var table = document.getElementById("main_table");
var n = table.rows.length;
var m = table.rows[0].cells.length;
var row = table.insertRow(n);
if (!localStorage['use_storage']) {
if (n === 1) {
localStorage["cells"] = JSON.stringify([{}]);
}
else if (n > 1) {
var cells = JSON.parse(localStorage["cells"]);
cells.push({});
localStorage["cells"] = JSON.stringify(cells);
}
}
var cell = row.insertCell(0);
cell.innerHTML = n;
for (j=1; j<m; j++) {
create_cell(n-1, j, row);
}
return row
}
function create_cell(i, j, row){
var cell = row.insertCell(j);
if (j == 1) {
cell.innerHTML = "<input size=10>";
}
else {
cell.innerHTML = "<input size=4>";
}
cell.addEventListener("change", function () {
var cells = JSON.parse(localStorage["cells"]);
cells[i.toString()][j.toString()] = cell.childNodes[0].value;
localStorage["cells"] = JSON.stringify(cells);
})
}
document.getElementById('create_row').onclick = create_row;
// restore a table
if (localStorage["last_session"]) {
localStorage["use_storage"] = true;
try {
var cells = JSON.parse(localStorage["cells"]);
var n = cells.length;
var table = document.getElementById("main_table")
for (i=0; i<n; i++) {
var row = create_row(true);
var cell = cells[i]
for (var key in cell) {
if (cell.hasOwnProperty(key)) {
var col = parseInt(key);
var val = cell[key];
row.cells[col].childNodes[0].value = val;
}
}
}
} catch (e) {
console.log("Catched error");
console.log(e);
}
if (localStorage["results"]) {
show_results();
}
localStorage['use_storage'] = false;
}
In my browser it works as it is supposed, that is after refreshing a page popup.html I have the state where I left (number of rows and values are preserved). However, in my chrome extension, after clicking to any area and thus reloading the extension, I have the initial empty table.
How can I preserve the table in this particular case?
I change the background of rows to dynamically for setinterval but not working.
if clicked the button, change class name as the rows in the table.
My codes:
HTML Code:
<table id="table">
<tr>
<td>AAA11</td>
<td>BBB11</td>
</tr>
..
..
</table>
<button id="btn">click</button>
CSS Codes
.red { background-color: red; }
JS Codes
var table = document.getElementById("table");
var rows = table.getElementsByTagName("tr");
// My func
function func(){
for (var i = 0; i < rows.length; i++) {
var index=0;
var c = rows[i].className;
if(c!="red") {
index=i;
} else {
index = i+1;
}
sec(index);
}
setInterval(func(), 2000);
}
// Change class name the rows
function sec(index){
for (var i = 0; i < rows.length; i++) {
if(index==i) {
rows[index].className="red";
}
if(index!=i ){
rows[index].className="null";
}
}
}
$('#btn').click(function(){
setInterval(func(), 2000);
});
you reset all other lines, except the last row with in the "sec" function.
if(index!=i ){
rows[index].className="null";
}
delete that part and it should work like you wanted
...tough i don't get what you want to do, since all you're doing is setting all rows backgrounds...if you want to reset the red ones, don't use your sec() function...try this instead:
function func(){
for (var i = 0; i < rows.length; i++) {
var index=0;
var c = rows[i].className;
if(c=="red") {
rows[i].className="";
} else {
rows[i].className="red";
}
}
}
[edit]
...after it's cleared what OP wanted to do:
http://jsfiddle.net/bzWV2/1/
[edit2]
...easier approach:
http://jsfiddle.net/bzWV2/2/
You could do something like that:
var $table = $("#table");
var $rows = $table.find("tr");
var func = function(){
var curIndex = $rows.filter('.red').index(),
nextIndex = curIndex === $rows.length - 1?0:++curIndex;
$rows.eq(nextIndex).addClass('red').siblings().removeClass('red');
}
$('#btn').click(function(){
$rows.eq(0).addClass('red');
setInterval(func, 2000);
});
DEMO
function highlight(element)
{
$('tr').removeClass('red');
el = (!element)? $('tr:first') : element;
el.addClass('red');
next_el = el.next('tr');
var el = (next_el.length == 0)? $('tr:first'): next_el;
setTimeout(function(){ highlight(el) }, 1000);
}
setTimeout(function(){ highlight() }, 1000);
http://fiddle.jshell.net/TFcUS/2/