I have Vue component with a table with users data:
<table class="worker-table" id="worker-table">
<tr>
<th><b>Phone number</b></th>
<th><b>Debet card</b></th>
<th><b>Money</b></th>
<th><b>Work hours</b></th>
<th><b>Responsible</b></th>
<th><b>Delete</b></th>
</tr>
<tr>
<tr v-for="worker in workers">
<td >
<div v-if="worker.parent == 1">
<strong v-on:click="toggleChildWorkers(worker)" class="pointer">
{{worker.phone}}(+{{child_workers[worker.id].length}})
</strong>
</div>
<div v-else>
{{worker.phone}}
</div>
</td>
<td>{{worker.debit_card}}</td>
<td>{{worker.money}}</td>
<td>{{worker.work_hours}}</td>
<td>{{worker.responsible_for_money}}</td>
<td>
<a href="#"
v-bind:disabled="(application.state > CLOSED_ST)? true: false"
class="btn btn-xs btn-danger"
v-on:click="deleteEntry(worker.id)"
>
Delete
</a>
</td>
</tr>
</table>
The button in the last <td> successfully deletes worker from the table.
Function toggleChildWorkers insert new rows with child workers and delete (hide, actually) them like this:
toggleChildWorkers(parentWorker)
{
var table = document.getElementById("worker-table");
var childWorkers = this.child_workers[parentWorker.id];
var childWorkersCount = childWorkers.length;
var parentWorkersIndexes = this.openAccordionsIndexes;
var dI = 0;
var userWantsCloseThisAccordion = false;
var indexOfClosingAcc = -1;
console.log(parentWorker);
for (var j = 0; j < parentWorkersIndexes.length; j++)
{
if (parentWorkersIndexes[j] < parentWorker.index)
{
dI += this.openAccordionsStrCount[j];
}
else if (parentWorkersIndexes[j] == parentWorker.index)
{
userWantsCloseThisAccordion = true;
indexOfClosingAcc = j;
}
}
if (userWantsCloseThisAccordion)
{
for (var i = 0; i < this.openAccordionsStrCount[indexOfClosingAcc]; i++)
{
table.deleteRow(parentWorker.index + 3 + dI);
}
this.openAccordionsIndexes.splice(indexOfClosingAcc, 1);
this.openAccordionsStrCount.splice(indexOfClosingAcc, 1);
return;
}
this.openAccordionsIndexes.push(parentWorker.index);
this.openAccordionsStrCount.push(childWorkersCount);
for (var i = 0; i < childWorkersCount; i++)
{
var row = table.insertRow(parentWorker.index + 3 + dI + i);
var cell1 = row.insertCell(0);
cell1.style.cssText = this.styleOfOpenAccStrings;
var cell2 = row.insertCell(1);
cell2.style.cssText = this.styleOfOpenAccStrings;
var cell3 = row.insertCell(2);
cell3.style.cssText = this.styleOfOpenAccStrings;
var cell4 = row.insertCell(3);
cell4.style.cssText = this.styleOfOpenAccStrings;
var cell5 = row.insertCell(4);
cell5.style.cssText = this.styleOfOpenAccStrings;
var cell6 = row.insertCell(5);
cell6.style.cssText = this.styleOfOpenAccStrings;
cell1.innerHTML = (childWorkers[i].phone === undefined) ?
'' : childWorkers[i].phone;
cell2.innerHTML = (childWorkers[i].debit_card === undefined) ?
'' : childWorkers[i].debit_card;
cell3.innerHTML = (childWorkers[i].money === undefined) ?
'' : childWorkers[i].money;
cell4.innerHTML = (childWorkers[i].work_hours === undefined) ?
'' : childWorkers[i].work_hours;
cell5.innerHTML = childWorkers[i].responsible_for_money;
cell6.innerHTML = "<a href=\"#\"\n" +
" v-bind:disabled=\"(application.state > CLOSED_ST)? true: false\"\n" +
" class=\"btn btn-xs btn-danger\"\n" +
" v-on:click=\"deleteEntry(props.row.index)\"\n" +
" >";
row.className = "openAccordionRow";
}
},
As you can see, I'm trying to embed buttons in the new cells of inserted rows (blue ones). But they are not displayed as it was intended and don't work at all.
How can I embed button with Vue code into new cell of inserted row?
I found a simple solution here. But I did't understand it at the beginning and use it without closure and it did't work as I expected. Then I found topic about Javascript infamous loop issue
and used the closure magic:
for (var i = 0; i < childWorkersCount; i++)
{
/* ...
...
...
*/
var btn = document.createElement('input');
btn.type = "button";
btn.className = "btn btn-xs btn-danger";
btn.value = "Delete " + childWorkers[i].phone;
var app = this;
var parentId = parentWorker.id;
btn.onclick = function (worker) {
return function () {
app.deleteEntryById(worker.id, parentId);
};
}(childWorkers[i]);
}
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>
I Create a Table Using this code,
<table class="table table-green table-hover" id="tblk"></table>
And I Use This JavaScrip Function (For A Button) to add Rows when I add data in to table,
function addRow() {
var custid = document.getElementById('InputCusomerID').value
var custname = document.getElementById('InputCusomerName').value
var itemid = document.getElementById('InputItemID').value
var table = document.getElementById('tblk')
var row = table.insertRow(0)
var cell1 = row.insertCell(0)
var cell2 = row.insertCell(1)
var cell3 = row.insertCell(2)
cell1.innerHTML = custid
cell2.innerHTML = custname
cell3.innerHTML = itemid
}
When I clicked a table row, I need to get a table Row value into my input text field
This Is my JavaScrip Function to get table rows to value into my text field..,
var table = document.getElementById('tblk'),
rIndex
for (var i = 1; i < table.rows.length; i++) {
table.rows[i].onclick = function () {
document.getElementById('InputCusomerID').value = this.cells[0].innerHTML
document.getElementById('InputCusomerName').value = this.cells[1].innerHTML
document.getElementById('InputItemID').value = this.cells[2].innerHTML
}
}
But My Code Is Not Working I Can't Get Table Row Value Into My Text Field.
Can You Help Me With That Problem..?
Thank You Very Much..!
function addRow() {
var custid = document.getElementById('InputCusomerID').value
var custname = document.getElementById('InputCusomerName').value
var itemid = document.getElementById('InputItemID').value
var table = document.getElementById('tblk')
var row = table.insertRow(0)
var cell1 = row.insertCell(0)
var cell2 = row.insertCell(1)
var cell3 = row.insertCell(2)
cell1.innerHTML = custid
cell2.innerHTML = custname
cell3.innerHTML = itemid
}
var table = document.getElementById('tblk'),
rIndex
for (var i = 1; i < table.rows.length; i++) {
table.rows[i].onclick = function() {
document.getElementById('InputCusomerID').value = this.cells[0].innerHTML
document.getElementById('InputCusomerName').value = this.cells[1].innerHTML
document.getElementById('InputItemID').value = this.cells[2].innerHTML
}
}
<table class="table table-green table-hover" id="tblk"></table>
I don't know exactly what you're trying to do, but it's not working because your click listener is being called before your table is populated. See my code.
function addRow() {
var custid = document.getElementById('InputCusomerID').value
var custname = document.getElementById('InputCusomerName').value
var itemid = document.getElementById('InputItemID').value
var table = document.getElementById('tblk')
var row = table.insertRow(0)
var cell1 = row.insertCell(0)
var cell2 = row.insertCell(1)
var cell3 = row.insertCell(2)
cell1.innerHTML = custid
cell2.innerHTML = custname
cell3.innerHTML = itemid
setListeners();
}
var table = document.getElementById('tblk'),
rIndex;
function setListeners() {
for (var i = 0; i < table.rows.length; i++) {
table.rows[i].addEventListener('click', function (e) {
console.log(e.target);
document.getElementById('InputCusomerID').value = "result: " + this.cells[0].innerHTML
document.getElementById('InputCusomerName').value = "result: " + this.cells[1].innerHTML
document.getElementById('InputItemID').value = "result: " + this.cells[2].innerHTML
});
}
}
addRow();
<input type="text" id="InputCusomerID" value="a" />
<input type="text" id="InputCusomerName" value="b" />
<input type="text" id="InputItemID" value="c" />
<table class="table table-green table-hover" id="tblk"></table>
HTML part... a To do list with 4 properties: the property "description" its not to be shown on the table. But when you dbclick on first cell(title), it should return all the 4 properties.
<body>
<h1 id="h1">ToDo Lijst</h1>
<label for="item">Titel</label><br>
<input type="text" id = "Item"><br><br>
<!--<p style="color:red; font-size:18px;" id="FoutInput"></p>-->
<label for = "aantal">Omschrijving</label><br>
<input class="desc" type="text" id="description"><br><br>
<label for="person">Toegewezen Person</label><br>
<input type="text" id = "person"><br><br>
<label for="deadline">Deadline</label><br>
<input type="text" id="deadline">
<button type = "button" onclick="Toevoegen()"><span>+</span></button>
<button type="button" onclick="Edit()" >Aanpassen</button>
<button style="background-color: crimson" onclick="Verwijderen()"><i class="fa fa-trash-o"></i></button>
<p style="color:red; font-size:15px;" id="FoutInput"></p>
<table id="table">
<tr>
<th>Titel</th>
<th>Toegewezen Person</th>
<th>Deadline</th>
</tr>
</table>
//javascript part
var rIndex,
table = document.getElementById("table");
function Toevoegen()
{
var newrow = table.insertRow(table.length),
cell1 = newrow.insertCell(0),
cell2=newrow.insertCell(1),
cell3=newrow.insertCell(2),
Titel = document.getElementById("Item").value,
person = document.getElementById("person").value,
deadline = document.getElementById("deadline").value;
//var description = document.getElementById("description").value;
if(Titel != "" && person != "" && deadline != "")
{
cell1.innerHTML = Titel;
cell2.innerHTML = person;
cell3.innerHTML = deadline;
document.getElementById("Item").value = ""; document.getElementById("person").value = "";
document.getElementById("deadline").value = "";
document.getElementById("description").value = "";
console.log(description);
var text1 = "Toegevoegd!";
document.getElementById("FoutInput").innerHTML = text1;
}
else{
cell1 = newrow.deleteCell(0);
cell2 = newrow.deleteCell(0,1);
var text = "Veld(en) mag(mogen) niet leeg blijven!";
document.getElementById("FoutInput").innerHTML = text;
}
selectedRowtoinput();
selectedCell();
}
function selectedCell(){
for(var i = 1;i<table.rows.length; i++){
table.rows[i].cells[0].ondblclick = function(){
var titel = document.getElementById("Item").value;
var person = document.getElementById("person").value;
var deadline = document.getElementById("deadline").value;
var description =
document.getElementById("description").value;
console.log(description);
alert("overzicht:" + "\n" + titel+ "\n" + person+ "\n" + deadline + "\n" + "omschrijving: " + description);
}
}
}
function selectedRowtoinput()
{
for(var i =1; i< table.rows.length; i++)
{
table.rows[i].onclick = function()
{
rIndex = this.rowIndex;
document.getElementById("Item").value =this.cells[0].innerHTML;
document.getElementById("person").value =this.cells[1].innerHTML;
document.getElementById("deadline").value =this.cells[2].innerHTML;
}
}
}
selectedRowtoinput();
I cant get data from:
var description =
document.getElementById("description").value;
console.log(description);
I just get an empty line. I get the info from the other 3 except this one...
Ok, I've updated your code and alter it with logic, that you DO create cell for description, but make in hidden, so it is not visible, but still holds the data, check example
var rIndex,
table = document.getElementById("table");
function Toevoegen()
{
var newrow = table.insertRow(table.length),
cell1 = newrow.insertCell(0),
cell2=newrow.insertCell(1),
cell3=newrow.insertCell(2),
cell4=newrow.insertCell(3),
Titel = document.getElementById("Item").value,
person = document.getElementById("person").value,
deadline = document.getElementById("deadline").value,
description = document.getElementById("description").value;
// Make hidden cell for description
cell4.className += " hidden";
if(Titel != "" && person != "" && deadline != "")
{
cell1.innerHTML = Titel;
cell2.innerHTML = person;
cell3.innerHTML = deadline;
// Put data in hidden cell
cell4.innerHTML = description;
document.getElementById("Item").value = "";
document.getElementById("person").value = "";
document.getElementById("deadline").value = "";
document.getElementById("description").value = "";
var text1 = "Toegevoegd!";
document.getElementById("FoutInput").innerHTML = text1;
}
else{
cell1 = newrow.deleteCell(0);
cell2 = newrow.deleteCell(0,1);
var text = "Veld(en) mag(mogen) niet leeg blijven!";
document.getElementById("FoutInput").innerHTML = text;
}
selectedRowtoinput();
selectedCell();
}
function selectedCell(){
for(var i = 1;i<table.rows.length; i++){
table.rows[i].cells[0].ondblclick = function(){
var titel = document.getElementById("Item").value;
var person = document.getElementById("person").value;
var deadline = document.getElementById("deadline").value;
var description = document.getElementById("description").value;
alert("overzicht:" + "\n" + titel+ "\n" + person+ "\n" + deadline + "\n" + "omschrijving: " + description);
}
}
}
function selectedRowtoinput()
{
for(var i =1; i< table.rows.length; i++)
{
table.rows[i].onclick = function()
{
rIndex = this.rowIndex;
document.getElementById("Item").value = this.cells[0].innerHTML;
document.getElementById("person").value = this.cells[1].innerHTML;
document.getElementById("deadline").value = this.cells[2].innerHTML;
document.getElementById("description").value = this.cells[3].innerHTML;
}
}
}
selectedRowtoinput();
.hidden {
display: none;
}
<body>
<h1 id="h1">ToDo Lijst</h1>
<label for="item">Titel</label><br>
<input type="text" id = "Item"><br><br>
<!--<p style="color:red; font-size:18px;" id="FoutInput"></p>-->
<label for = "aantal">Omschrijving</label><br>
<input class="desc" type="text" id="description"><br><br>
<label for="person">Toegewezen Person</label><br>
<input type="text" id = "person"><br><br>
<label for="deadline">Deadline</label><br>
<input type="text" id="deadline">
<button type = "button" onclick="Toevoegen()"><span>+</span></button>
<button type="button" onclick="Edit()" >Aanpassen</button>
<button style="background-color: crimson" onclick="Verwijderen()"><i class="fa fa-trash-o"></i></button>
<p style="color:red; font-size:15px;" id="FoutInput"></p>
<table id="table">
<tr>
<th>Titel</th>
<th>Toegewezen Person</th>
<th>Deadline</th>
</tr>
</table>
I have been stuck on an issue where I am trying to use Javascript to add and remove a row from a table.
I got the add part working, the delete somewhat. The delete fails if you delete the first row or a row in the middle (live code can be seen here
I uploaded its code on PasteBin
<script type="text/javascript">
var itemNumber = 0
var currentRow = 0;
var selectedRow = 0;
function theIndex(theRow){
selectedRow = theRow;
}
document.getElementById("addItem").addEventListener("click", function(){
if (document.getElementById('whatToDo').value != ""){
currentRow++;
var table = document.getElementById('myList');
var row = table.insertRow(currentRow);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
itemNumber++;
// alert(currentRow);
// cell1.innerHTML = itemNumber;
cell2.innerHTML = document.getElementById('whatToDo').value;
cell3.innerHTML = document.getElementById('whenToDo').value;
cell4.innerHTML = document.getElementById('whereToDo').value;
row.addEventListener('click', theIndex.bind(null, currentRow));
document.getElementById('whatToDo').value = "";
document.getElementById('whenToDo').value = "";
document.getElementById('whereToDo').value = "";
}
});
document.getElementById("removeItem").addEventListener("click", function(){
// var theRow = document.getElementById('whatToMark').value;
var theRow = selectedRow;
alert("index: " +theRow + " elements: " + currentRow);
if (theRow > 0){
document.getElementById("myList").deleteRow(theRow);
document.getElementById('whatToMark').value = "";
currentRow--;
itemNumber--;
}
selectedRow = 0;
});
document.getElementById("markAsDone").addEventListener("click", function(){
// var theRow = document.getElementById('whatToMark').value;
var theRow = selectedRow;
alert("index: " +theRow + " elements: " + currentRow);
var table = document.getElementById('myList');
if (theRow != 0){
table.rows[theRow].style.setProperty("text-decoration", "line-through");
document.getElementById('whatToMark').value = "";
}
selectedRow = 0;
});
</script>
I am learning Javascript and wanted to do more than the exercise that was being given by adding new features to it.
Your approach to mark the current selected row has some issues:
row.addEventListener('click', theIndex.bind(null, currentRow));
Instead of using a global variable I suggest to use a row attribute (or class). Hence, change that line to:
row.addEventListener('click', function(e) {
document.querySelectorAll('tr[selected]').forEach(function(item) {
item.removeAttr('selected');
})
row.setAttribute('selected', true);
});
Add the attribute selected for the current row and remove the same attribute for other rows.
In this way, when you need to get the current selected row you can simply:
var rSelected = document.querySelector('tr[selected]');
var theRow = (rSelected == null) ? 0 : rSelected.rowIndex;
var itemNumber = 0
var currentRow = 0;
var selectedRow = 0;
function theIndex(theRow) {
selectedRow = theRow;
}
document.getElementById("addItem").addEventListener("click", function () {
if (document.getElementById('whatToDo').value != "") {
currentRow++;
var table = document.getElementById('myList');
var row = table.insertRow(currentRow);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
itemNumber++;
// alert(currentRow);
// cell1.innerHTML = itemNumber;
cell2.innerHTML = document.getElementById('whatToDo').value;
cell3.innerHTML = document.getElementById('whenToDo').value;
cell4.innerHTML = document.getElementById('whereToDo').value;
//row.addEventListener('click', theIndex.bind(null, currentRow));
row.addEventListener('click', function(e) {
document.querySelectorAll('tr[selected]').forEach(function(item) {
item.removeAttr('selected');
})
row.setAttribute('selected', true);
});
document.getElementById('whatToDo').value = "";
document.getElementById('whenToDo').value = "";
document.getElementById('whereToDo').value = "";
}
});
document.getElementById("removeItem").addEventListener("click", function () {
// var theRow = document.getElementById('whatToMark').value;
var rSelected = document.querySelector('tr[selected]');
var theRow = (rSelected == null) ? 0 : rSelected.rowIndex;
if (theRow > 0) {
document.getElementById("myList").deleteRow(theRow);
//document.getElementById('whatToMark').value = "";
currentRow--;
itemNumber--;
}
selectedRow = 0;
});
document.getElementById("markAsDone").addEventListener("click", function () {
// var theRow = document.getElementById('whatToMark').value;
var theRow = selectedRow;
alert("index: " + theRow + " elements: " + currentRow);
var table = document.getElementById('myList');
if (theRow != 0) {
table.rows[theRow].style.setProperty("text-decoration", "line-through");
document.getElementById('whatToMark').value = "";
}
selectedRow = 0;
});
<div class="container">
<div class="row">
<div class="col-lg-4 col-sm-6">
<table class="table table-hover">
<tr>
<td colspan="3">
<h1>To Do List Example</h1>
</td>
</tr>
<tr>
<th><label>Item</label></th>
<th><label>Date</label></th>
<th><label>Location</label></th>
</tr>
<tr>
<td>
<input type="text" id="whatToDo" value="">
</td>
<td>
<input type="date" id="whenToDo" value="">
</td>
<td>
<input type="text" id="whereToDo" value="">
</td>
</tr>
<tr>
<td>
<button id="addItem" class="btn btn-default btn-primary active">
<i class="fas fa-plus"></i> Add This Item
</button>
</td>
<td>
<button id="markAsDone" class="btn btn-default ">
<i class="fas fa-check"></i> Mark As Done
</button>
</td>
<td>
<button id="removeItem" class="btn btn-default">
<i class="fas fa-trash-alt"></i> Remove Item
</button>
</td>
</tr>
</table>
</div>
</div>
<div class="row">
<div class="col-lg-4 col-sm-6">
<table class="table table-hover" id="myList">
<tr>
<th><label></label></th>
<th><label>Event</label></th>
<th><label>Date</label></th>
<th><label>Location</label></th>
</tr>
</table>
</div>
</div>
</div>
This line is throwing a null value error:
document.getElementById('whatToMark').value = "";
Neither in your JS, nor in your HTML, do you ever set an element to the ID of whatToMark.
I got this project for school, I need to load data from sessionStorage in a html table when my .html loads (not only from cache).
I insert new data in sessionStorage from another .html, i need to save it dynamically (for example the first row of my table is rfc0, razon_social0, direccion_fiscal0, the next row is rfc1, razon_social1, direccion_fiscal1, etc...), I use this Javascript function to save my data:
function getInfo() {
if (sessionStorage.contador){
var i = parseInt(sessionStorage.contador);
}
else{
sessionStorage.setItem('contador', "0");
var i = parseInt(sessionStorage.contador);
}
var rfc = document.getElementById('RFC').value.toUpperCase();
sessionStorage.setItem('rfc' + i, rfc);
var razon_social = document.getElementById('razon_social').value;
sessionStorage.setItem('razon_social' + i, razon_social);
var domicilio_fiscal = document.getElementById('domicilio_fiscal').value;
sessionStorage.setItem('domicilio_fiscal' + i, domicilio_fiscal);
var banco = document.getElementById('banco').value;
sessionStorage.setItem('banco' + i, banco);
var numero_cuenta = document.getElementById('numero_cuenta').value;
sessionStorage.setItem('numero_cuenta' + i, numero_cuenta);
i++;
sessionStorage.setItem('contador', i);
}
In my body onpageshow I use this function to check the Storage support and call the data:
function checkStorage() {
if(typeof(Storage) !== "undefined") {
if(sessionStorage.flag) {
agregarDatos();
}
}
else {
alert('Sorry! No Web Storage support...')
}
}
My function agregarDatos() is:
function agregarDatos() {
var table = document.getElementById("tabla_clientes");
var i = parseInt(sessionStorage.contador);
var conta = 0;
while(conta <= i){
var row = table.insertRow(-1);
var cell0 = row.insertCell(0)
var cell1 = row.insertCell(1);
var cell2 = row.insertCell(2);
var cell3 = row.insertCell(3);
var cell4 = row.insertCell(4);
cell0.innerHTML = '<input class="check" type="checkbox" onClick="validateButton()">';
cell1.innerHTML = sessionStorage.getItem('rfc' + conta);
cell2.innerHTML = sessionStorage.getItem('razon_social' + conta);
cell3.innerHTML = sessionStorage.getItem('domicilio_fiscal' + conta);
cell4.innerHTML = '<input class="editar" type="button" value="Editar">';
conta++;
}
}
When I test this, got nothing even when I add an element from the first time, I can't figure what's wrong.
If I save the data without ID I can only add one row with the last data stored.
P.D. Only I can use Javascript...
Your code has a couple of errors:
In order to populate the table you are checking the value of sessionStorage.flag that is not set anywhere in your code. As it is not defined, the if condition is false and agregarDatos() will never be called. To fix this check for sessionStorage.contador (as it is done in the JSFiddle specified below)
In agregarDatos() the loop goes one extra iteration because you are doing conta <= i when you should be doing conta < i.
This would be the code (with some mock HTML and getInfo call). The modified lines are pointed with comments:
function getInfo() {
if (sessionStorage.contador){
var i = parseInt(sessionStorage.contador);
} else {
sessionStorage.setItem('contador', "0");
var i = parseInt(sessionStorage.contador);
}
var rfc = document.getElementById('RFC').value.toUpperCase();
sessionStorage.setItem('rfc' + i, rfc);
var razon_social = document.getElementById('razon_social').value;
sessionStorage.setItem('razon_social' + i, razon_social);
var domicilio_fiscal = document.getElementById('domicilio_fiscal').value;
sessionStorage.setItem('domicilio_fiscal' + i, domicilio_fiscal);
var banco = document.getElementById('banco').value;
sessionStorage.setItem('banco' + i, banco);
var numero_cuenta = document.getElementById('numero_cuenta').value;
sessionStorage.setItem('numero_cuenta' + i, numero_cuenta);
i++;
sessionStorage.setItem('contador', i);
}
function agregarDatos() {
var table = document.getElementById("tabla_clientes");
var i = parseInt(sessionStorage.contador);
var conta = 0;
// Loop from 0 to elems-1 (before it was iterating one extra time)
while(conta < i){
var row = table.insertRow(-1);
var cell0 = row.insertCell(0)
var cell1 = row.insertCell(1);
var cell2 = row.insertCell(2);
var cell3 = row.insertCell(3);
var cell4 = row.insertCell(4);
cell0.innerHTML = '<input class="check" type="checkbox" onClick="validateButton()">';
cell1.innerHTML = sessionStorage.getItem('rfc' + conta);
cell2.innerHTML = sessionStorage.getItem('razon_social' + conta);
cell3.innerHTML = sessionStorage.getItem('domicilio_fiscal' + conta);
cell4.innerHTML = '<input class="editar" type="button" value="Editar">';
conta++;
}
}
function checkStorage() {
if(typeof(Storage) !== "undefined") {
// sessionStorage.flag does not exist, use a value that you know will exist
if(sessionStorage.contador) {
agregarDatos();
}
}
else {
alert('Sorry! No Web Storage support...')
}
}
window.onload = function() {
console.log(1);
checkStorage();
}
<div>
<input type="text" id="RFC" placeholder="RFC" /><br/>
<input type="text" id="razon_social" placeholder="Razón Social"/><br/>
<input type="text" id="domicilio_fiscal" placeholder="Domicilio Fiscal"/><br/>
<input type="text" id="banco" placeholder="Banco"/><br/>
<input type="text" id="numero_cuenta" placeholder="Número de Cuenta"/><br/>
<input type="button" value="Add to table" onclick="getInfo()"/>
</div>
<table id="tabla_clientes"></table>
That window is sandboxed so you cannot see it working on here, but you can on this JSFiddle.