I have a dynamic table. Data comes from inputs by Create button click.
If at least one row includes current input ID-field value (not inserted yet) program should forbid row insertion.
I tried to add checkId() logic but it didn't work for me:
checkId = () => {
var isDuplicate = false;
var idVal = inputs[0].value;
if (textbox.value.includes(idVal)){
isDuplicate = true;
row.remove();
alert("Pease, enter unique ID")
}
return isDuplicate;
}
Is there any way to implement this logic within existing code (no jQuery)?
Here are both html and js:
let headerArr = new Array();
headerArr = ['ID', 'Fname', 'Lname', 'Age'];
//console.log(headerArr.length)
//inputs
var div = document.getElementById('enter');
var inputs = div.getElementsByTagName('input')
var count = 0;
createTable = () => {
let storage = document.createElement('table');
storage.setAttribute('id', 'storage'); //set the table ID
let row = storage.insertRow(-1);
for (let h = 0; h < headerArr.length; h++) { //table header
let headCols = document.createElement('th');
headCols.innerHTML = headerArr[h];
row.appendChild(headCols);
}
let div = document.getElementById('dynamicTable');
div.appendChild(storage); //add the table to the page
}
/* checkId = () => {
var isDuplicate = false;
var idVal = inputs[0].value;
//textbox = document.createElement('input')
if (textbox.value.includes(idVal)){
isDuplicate = true;
row.remove();
alert("Pease, enter unique ID")
}
return isDuplicate;
} */
//add a new row to the table
addEnd = () => {
let table = document.getElementById('storage');
var rowCount = table.rows.length; //get table row count
var row = table.insertRow(rowCount)
var textbox;
// if((!checkId()) && rowCount > 1){
for (let c = 0; c <= headerArr.length - 1; c++) {
var cell = document.createElement('td');
cell = row.insertCell(c);
textbox = document.createElement('input');
textbox.setAttribute('type', 'text');
textbox.setAttribute('readonly', true);
textbox.setAttribute('value', inputs[c].value);
cell.appendChild(textbox);
}
// }
}
let createBtn = document.getElementById('create-btn');
createBtn.addEventListener('click', addEnd, false);
<!DOCTYPE html>
<html>
<head>
<title>Table</title>
<style>
table {
width: 100px;
border-spacing: 10px;
padding: 10px;
}
table,
th,
td {
border: 1px solid gray;
border-collapse: collapse;
padding: 2px 3px;
text-align: left;
}
.enter {
display: block;
float: right;
margin-bottom: 10px
}
}
</style>
</head>
<body onload="createTable()">
<div id="dynamicTable"></div>
<div id="enter" class="enter">
<p>ID:<br>
<input class="enter__id" type="text" id="id"></input>
<br>
<p>First name:<br>
<input class="enter__name type=" text " id="name "></input>
<br>
<p>Last name:<br>
<input class="enter__surname type="text" id="surname"></input>
<br>
<p>Age:<br>
<input class="enter__age" type="text" id="age"></input>
<br>
<button id="create-btn">Create</button>
<button id="update-btn">Update</button>
</div>
<script type="text/javascript" src="script.js"></script>
</body>
</html>
Please, help me to find the right way to solve it.
if (textbox.value.includes(idVal))
Your condition isn't valid, because you try to get .value from a variable that is undefined in your context.
I fix your js code :
let headerArr = new Array();
headerArr = ['ID', 'Fname', 'Lname', 'Age'];
//console.log(headerArr.length)
//inputs
var div = document.getElementById('enter');
var inputs = div.getElementsByTagName('input')
var count = 0;
createTable = () => {
let storage = document.createElement('table');
storage.setAttribute('id', 'storage'); //set the table ID
let row = storage.insertRow(-1);
for (let h = 0; h < headerArr.length; h++) { //table header
let headCols = document.createElement('th');
headCols.innerHTML = headerArr[h];
row.appendChild(headCols);
}
let div = document.getElementById('dynamicTable');
div.appendChild(storage); //add the table to the page
}
checkId = () => {
var idVal = inputs[0].value;
for (var i = 0; i < document.getElementsByClassName('id_cells').length; i++) {
let el_id = document.getElementsByClassName('id_cells');
if (el_id.value = idVal) {
alert("Pease, enter unique ID");
return true
}
}
return false;
}
//add a new row to the table
addEnd = () => {
let table = document.getElementById('storage');
var rowCount = table.rows.length; //get table row count
var row = table.insertRow(rowCount)
if ((!checkId()) && rowCount > 1) {
for (let c = 0; c <= headerArr.length - 1; c++) {
var cell = document.createElement('td');
cell = row.insertCell(c);
textbox = document.createElement('input');
textbox.setAttribute('type', 'text');
textbox.setAttribute('readonly', true);
textbox.setAttribute('value', inputs[c].value);
if (c == 0) {
textbox.setAttribute('class', 'id_cells');
}
cell.appendChild(textbox);
}
}
}
let createBtn = document.getElementById('create-btn');
createBtn.addEventListener('click', addEnd, false);
When you create your cells, if it's the first of the row (where the id should be displayed), I add a class to the cell to keep a reference. When you need to check for duplicate id, you get all the tag with the class i set beforehand and check their id in a loop.
I hope it solved your issue
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>
From this code, once you pressed the button, it will generate a new table row with 16 cells. I came up with the ideal ID for each cell, in the pattern of 'RxCx', and I'd like to ask everyone what code's still missing to let it be each cell's ID?
Thanks a lot for your help!
const tab = document.getElementById("tab");
const btn1 = document.getElementById("btn1");
var rowCount = 0;
var cellCount = 0;
btn1.addEventListener('click', () => {
var row = tab.insertRow(-1);
rowCount++;
for (var i = 0; i <= 15; i++) {
row.insertCell(i);
cellCount = i + 1;
var ID = "";
ID = ID + "R" + rowCount + "C" + cellCount;
console.log(ID);
}
});
<body>
<button id="btn1">Add</button>
<table id="tab"></table>
</body>
One approach is as follows, with explanatory comments in the JavaScript:
const tab = document.getElementById("tab");
const btn1 = document.getElementById("btn1");
let rowCount = 0;
let cellCount = 0;
btn1.addEventListener('click', () => {
let row = tab.insertRow(-1);
rowCount++;
for (let i = 0; i <= 15; i++) {
// getting a reference to the inserted cell:
let c = row.insertCell(i);
cellCount = i + 1;
let ID = "";
// using += to append the right side of the assignment to the end
// of the existing value:
ID += "R" + rowCount + "C" + cellCount;
// using c.id to update the id property of the c element
// to the value held in the ID variable:
c.id = ID;
}
});
td {
min-block-size: 2em;
min-inline-size: 2em;
}
td[id]::before {
content: attr(id);
}
<body>
<button id="btn1">Add</button>
<table id="tab"></table>
</body>
JS Fiddle demo.
I would probably modify the approach to remove the (unnecessary) counters, and instead make use of the HTMLTableRowElement.rowIndex and HTMLTableCellElement.cellIndex properties of the nodes that you're already creating:
const tab = document.getElementById("tab");
const btn1 = document.getElementById("btn1");
btn1.addEventListener('click', () => {
let row = tab.insertRow(-1);
for (let i = 0; i <= 15; i++) {
let c = row.insertCell(i);
// using a template-literal string to concatenate JavaScript
// variables into the string, here we increment the value of
// rowIndex and cellIndex since it seems you want to start
// counting at 1, rather 0 (as JavaScript does by default):
c.id = `R${++row.rowIndex}C${++c.cellIndex}`;
}
});
td {
min-block-size: 2em;
min-inline-size: 2em;
}
td[id]::before {
content: attr(id);
}
<body>
<button id="btn1">Add</button>
<table id="tab"></table>
</body>
JS Fiddle demo.
References:
Element.id.
HTMLTableCellElement.cellIndex.
HTMLTableRowElement.rowIndex.
Template literals.
You can set the ID of the td via setAttribute(), e.g.
const td = row.insertCell(i);
td.setAttribute("id", "some-id");
It's also possible to access the cells by row- and column index instead of ID, e.g.
const td = tab.rows[0].cells[10];
const tab = document.getElementById("tab");
const btn1 = document.getElementById("btn1");
let rowCount = 0;
btn1.addEventListener('click', () => {
const row = tab.insertRow(-1);
rowCount++;
for (let i = 0; i <= 15; i++) {
const cell = row.insertCell(i);
const id = "R" + rowCount + "C" + i;
cell.setAttribute("id", id);
console.log(id);
}
console.log("0|10: " + document.getElementById("R1C10"));
// Directly access cell via row- and column index
console.log("0|10: " + tab.rows[0].cells[10]);
});
<body>
<button id="btn1">Add</button>
<table id="tab"></table>
</body>
You can set the Id or other properties when you call insertCell
e.g.
row.insertCell(i).id = 'YourId'
I am trying to build a grade book web app. I wanted to be able to edit the table cells to input grades, but I can't set it to readonly. What am I doing wrong?
I tried changing the code in the save button, but nothing works. I cant seem to get the input tags for some reason.Am I missing something? Is there another way to try to set the cells to readOnly? I tried getting the td tags, but that didn't work.
var myTable = document.getElementById("myTable");
var r = 0;
var c = 1;
function addRow() {
//insert a row
var row = myTable.insertRow(r);
//insert cells into a row
var cell = row.insertCell(0);
cell.innerHTML = "Students[i]";
r++;
}
function addColumn() {
//add new cell to each row
var allRows = document.getElementsByTagName("tr");
for (var i = 0; i < allRows.length; i++) {
row2 = allRows[i];
cell2 = allRows[i].insertCell(c);
cell2.innerHTML = "Puff";
}
}
function editCell() {
var allCells = document.getElementsByTagName("td");
for (var j = 0; j < allCells.length; j++) {
//clear text, then put in input box
allCells[j].innerHTML = "";
var myInput = document.createElement("input");
myInput.type = "text";
myInput.readOnly = false;
allCells[j].appendChild(myInput);
}
}
function saveData() {
//turn all inputs into readOnly
var allInputs = document.getElementsByTagName("td");
for (var k = 0; k < allInputs.length; k++) {
allInputs[k].id = "inpoot";
document.getElementById("inpoot").readOnly = true;
}
//document.getElementsByTagName("input").readOnly = true;
}
table,
th,
td {
border: 1px solid black;
border-collapse: collapse;
}
<table id="myTable"></table>
<button onClick="addRow()">Students</button>
<button onClick="addColumn()">Days</button>
<button onClick="editCell()">Edit</button>
<button onClick="savaData()">Save</button>
HTML IDs must be globally unique within a document. Since you're setting the ID to inpoot for each one, then the getElementById call is always going to be selecting the same element. Also, these elements are the tds, not the inputs themselves.
Try changing your save function thusly:
function saveData(){
//turn all inputs into readOnly
document.querySelectorAll("td > input").forEach(input => {
input.readOnly = true;
});
}
Is there another way to try to set the cells to readOnly?
Use this :
JS :
var myInput = document.createElement("input");
myInput.classList.add("readOnly-input");
CSS :
.readOnly-input{ pointer-events: none; }
The user can't interact when pointer-events are set to none. Let me know if you need more explaination.
I have a table that is created by javascript when it obtains data from the data base, this is the function
function gotCData(snapshot){
snapshot.forEach(userSnapshot => {
var confirmed = userSnapshot.val().confirmed;
var date = userSnapshot.val().date;
var deaths = userSnapshot.val().deaths;
var recovered = userSnapshot.val().recovered;
//console.log(confirmed, date, deaths, recovered);
var local = k;
var csvDate = date;
var population = recovered;
var totalCases = confirmed;
var totalDeaths = deaths;
//console.log(location);
var tr = document.createElement('tr');
var td1 = document.createElement('td');
var td2 = document.createElement('td');
var td3 = document.createElement('td');
var td4 = document.createElement('td');
var td5 = document.createElement('td');
var tdLocal = document.createTextNode(local);
var tdPopulation = document.createTextNode(population);
var tdTotalCases = document.createTextNode(totalCases);
var tdTotalDeaths = document.createTextNode(totalDeaths);
var tdDate = document.createTextNode(csvDate);
td1.appendChild(tdLocal)
td2.appendChild(tdPopulation)
td3.appendChild(tdTotalCases)
td4.appendChild(tdTotalDeaths)
td5.appendChild(tdDate)
var tRow1 = document.getElementById("displayCorona").appendChild(td1);
var tRow2 = document.getElementById("displayCorona").appendChild(td2);
var tRow3 = document.getElementById("displayCorona").appendChild(td3);
var tRow4 = document.getElementById("displayCorona").appendChild(td4);
var tRow5 = document.getElementById("displayCorona").appendChild(td5);
//Writes the Table Row then the Divs after
document.getElementById("displayCorona").appendChild(tr, tRow1, tRow2, tRow3, tRow4, tRow5);
});
}
I have a search function :
function search(){
// Declare variables
var input, filter, table, tr, td, i, txtValue;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
table = document.getElementById("displayCorona");
tr = table.getElementsByTagName("tr");
// Loop through all table rows, and hide those who don't match the search query
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td1")[0];
if (td) {
txtValue = td.textContent || td.innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1) {
tr[i].style.display = "";
} else {
tr[i].style.display = "none";
}
}
}
}
The tables are created when I loop through each node in a Firebase database. The search function is from W3Schools but im not sure why it is not searching the table that is created by the above function.
Here's some code for you to look at.
"use strict";
function newEl(tag){return document.createElement(tag)}
function byId(id){return document.getElementById(id)}
window.addEventListener('load', onLoad, false);
function onLoad(evt)
{
var inputStr = "I have a table that is created by javascript when it obtains data from the data base, this is the function";
document.body.appendChild( makeTable(inputStr) );
byId('goBtn').addEventListener('click', onGoBtn, false);
}
function makeTable(input)
{
let tbl = newEl('table');
input = input.replace(',', '');
let words = input.split(' ');
let nWords = words.length;
let nRows = parseInt(nWords/5) + nWords%5;
for (var j=0; j<nRows; j++)
{
let tr = newEl('tr');
for (var col=0; col<5; col++)
{
let td = newEl('td');
td.textContent = words[j*5 + col];
tr.appendChild(td);
}
tbl.appendChild(tr);
}
return tbl;
}
function highlightContainingCells(input, highlightClassname)
{
let cells = document.querySelectorAll('td');
cells.forEach( cellFunc );
function cellFunc(curCell)
{
if (input == curCell.textContent)
curCell.classList.add(highlightClassname);
else
curCell.classList.remove(highlightClassname);
}
}
function onGoBtn(evt)
{
let str = byId('searchStr').value;
highlightContainingCells(str, "found");
}
td
{
color: #333;
background-color: #ddd;
}
td.found
{
color: #ddd;
background-color: #333;
}
<input id='searchStr' value='javascript'/><button id='goBtn'>SEARCH</button></br>
There were so many wrong things.
You had not specified what data type snapshot is. Is it array or something else? I assumed it to be array of JSON objects, where each object denotes a row in your table.
I did not understand the use of .val() method. I removed it completely.
The table being generates was not in correct format. You were appending tr to table. But instead of appending td to tr you were also appending them to table. I have corrected that also.
There was an undefined variable k which was being used to set local.
display:block style on tr was displaying table in a weird way once rows are eliminated. I changed it to display:table-row instead, which is ideal for table-rows
function gotCData(snapshot) {
snapshot.forEach(userSnapshot => {
var confirmed = userSnapshot.val().confirmed;
var date = userSnapshot.val().date;
var deaths = userSnapshot.val().deaths;
var recovered = userSnapshot.val().recovered;
var local = userSnapshot.local; // we will look at this later
// console.log(confirmed, date, deaths, recovered);
// var local = k;
var csvDate = date;
var population = recovered;
var totalCases = confirmed;
var totalDeaths = deaths;
//console.log(location);
var tr = document.createElement('tr');
var td1 = document.createElement('td');
var td2 = document.createElement('td');
var td3 = document.createElement('td');
var td4 = document.createElement('td');
var td5 = document.createElement('td');
var tdLocal = document.createTextNode(local);
var tdPopulation = document.createTextNode(population);
var tdTotalCases = document.createTextNode(totalCases);
var tdTotalDeaths = document.createTextNode(totalDeaths);
var tdDate = document.createTextNode(csvDate);
td1.appendChild(tdLocal)
td2.appendChild(tdPopulation)
td3.appendChild(tdTotalCases)
td4.appendChild(tdTotalDeaths)
td5.appendChild(tdDate)
tr.appendChild(td1)
tr.appendChild(td2)
tr.appendChild(td3)
tr.appendChild(td4)
tr.appendChild(td5)
// Writes the Table Row then the Divs after
document.getElementById("displayCorona").appendChild(tr);
});
}
function search() {
// Declare variables
var input, filter, table, tr, td, i, txtValue;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
table = document.getElementById("displayCorona");
tr = table.querySelectorAll("tr:not(.table-head)");
// Loop through all table rows, and hide those who don't match the search query
var found
for (i = 0; i < tr.length; i++) {
tds = tr[i].getElementsByTagName("td")
if (tds) {
found = false
for (j = 0; j < tds.length && found == false; j++) {
td = tds[j];
txtValue = td.textContent || td.innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1) {
tr[i].style.display = "table-row";
found = true
break
}
}
if (found == false) tr[i].style.display = "none";
}
}
}
// This is used for testing only
// window.onload = () => {
// snapshot = firebaseToArray(firebaseJSON)
// gotCData(snapshot)
// }
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
margin-top: 20px;
}
td, th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
tr:nth-child(even) {
background-color: #dddddd;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<input type="text" id="myInput">
<button type="submit" onclick="search()">Search</button>
<table id="displayCorona">
<tr class="table-head">
<th>Location</th>
<th>Population</th>
<th>Total cases</th>
<th>Total deaths</th>
<th>Date</th>
</tr>
</table>
</body>
</html>
Some friendly advice:
I see you have extracted data from snapshot and assign them twice to variables, for say you first extract date from snapshot and then assign it to csvDate, while you could directly extract date to csvDate
You were creating text nodes for td, assigning them values and appending them to corresponding td node. You could directly insert data using innerHTML or innerText for example, td1.innerText = local. No need to create textNodes and append them!
It seems like you directly copy-pasted code for search function from w3schools. Please review such codes after using.
Use developer console to find common errors. Debugging your code can solves many common problems, so get familiar with it.
I am working on a thing there a user can input some data, date, activity, and time. And when the user clicks on add, it adds it to a table. This table contains a 4 cell (checkbox) that is checked. Now the point is that a user can add many rows with data and then click on the checkbox, if its unchecked it will not be send to JSON string, but the rows that are checked should be send!
The problem is if i have 1 row thats green and 1 row thats red its still print out all the rows when i click on send greenmarked data.
Below is the code:
<!doctype html>
<html lang="en">
<head>
<style>
table, td {
border: 1px solid black;
padding: 0 40px 0 40px;
}
tr {
background-color: #00FF00;
}
.Green {
background-color: #00FF00;
}
.Red {
background-color: #FF0000;
}
</style>
<meta charset="utf-8">
</head>
<body>
<form>
Date: <input type="text" id="Datum" name="Date">
Activ: <input type="text" id="Activity" name="Activ">
Time: <input type="text" id="time" name="Time">
</form>
<button onclick="AddRow()">Add Data!</button>
<table id="myTable">
<tr>
<td>Date</td>
<td>Activity</td>
<td>Time</td>
<td>Done?</td>
</tr>
</table>
<button id="buttonforsend" onclick="SendData()">Send greenmarked data! </button>
<script>
function AddRow()
{
var $check = document.createElement("INPUT");
$check.setAttribute("type", "checkbox");
$check.setAttribute("checked", "true");
$check.setAttribute("id", "checks");
$check.addEventListener("click", toggleClass);
function toggleClass() {
console.log("clicked");
if (this.checked == true)
{
this.parentNode.parentNode.className = "Green";
}
else
{
this.parentNode.parentNode.className = "Red";
}
}
var date = document.getElementById("Datum");
var activity = document.getElementById("Activity");
var time = document.getElementById("time");
var table = document.getElementById("myTable");
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
row.insertCell(0).innerHTML= date.value;
row.insertCell(1).innerHTML= activity.value;
row.insertCell(2).innerHTML= time.value;
row.insertCell(3).appendChild($check).value;
}
function addTable() {
var myTableDiv = document.getElementById("myDynamicTable");
var table = document.createElement('TABLE');
table.border='1';
var tableBody = document.createElement('TBODY');
table.appendChild(tableBody);
for (var i=0; i<3; i++){
var tr = document.createElement('TR');
tableBody.appendChild(tr);
for (var j=0; j<4; j++){
var td = document.createElement('TD');
td.width='75';
td.appendChild(document.createTextNode("Cell " + i + "," + j));
tr.appendChild(td);
}
}
myTableDiv.appendChild(table);
}
function CheckData() {
var $arr = [];
var tb = document.getElementById("myTable");
var check = document.getElementById("checks");
for (var i = 0, row; row = tb.rows[i]; i++) {
for (var j = 0, col; col = row.cells[j]; j++) {
if(check.checked == true) {
$arr.push(col.firstChild.nodeValue);
}
}
}
return $arr;
}
function SendData()
{
var obj = {test: CheckData()};
var jsonString = "jsonString=" + (JSON.stringify(obj));
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST","JSON_H.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form- urlencoded");
xmlhttp.setRequestHeader("Content-Length", jsonString.length);
xmlhttp.onreadystatechange = function()
{
if(xmlhttp.readyState === 4 && (xmlhttp.status === 200)){
alert(xmlhttp.responseText);
}
};
xmlhttp.send(jsonString);
}
</script>
</body>
</html>
You can find all the checked checkboxes in the table, and then add only the values of rows with a checked checkbox
function AddRow() {
var $check = document.createElement("INPUT");
$check.setAttribute("type", "checkbox");
$check.setAttribute("checked", "true");
$check.setAttribute("class", "checks");
$check.addEventListener("click", toggleClass);
function toggleClass() {
if (this.checked == true) {
this.parentNode.parentNode.className = "Green";
} else {
this.parentNode.parentNode.className = "Red";
}
}
var date = document.getElementById("Datum");
var activity = document.getElementById("Activity");
var time = document.getElementById("time");
var table = document.getElementById("myTable");
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
row.insertCell(0).innerHTML = date.value;
row.insertCell(1).innerHTML = activity.value;
row.insertCell(2).innerHTML = time.value;
row.insertCell(3).appendChild($check).value;
}
function addTable() {
var myTableDiv = document.getElementById("myDynamicTable");
var table = document.createElement('TABLE');
table.border = '1';
var tableBody = document.createElement('TBODY');
table.appendChild(tableBody);
for (var i = 0; i < 3; i++) {
var tr = document.createElement('TR');
tableBody.appendChild(tr);
for (var j = 0; j < 4; j++) {
var td = document.createElement('TD');
td.width = '75';
td.appendChild(document.createTextNode("Cell " + i + "," + j));
tr.appendChild(td);
}
}
myTableDiv.appendChild(table);
}
function CheckData() {
var $arr = [];
var tb = document.getElementById("myTable");
var checks = tb.querySelectorAll(".checks"),
chk, tr;
for (var i = 0; i < checks.length; i++) {
chk = checks[i];
if (chk.checked) {
tr = chk.closest ? chk.closest('tr') : chk.parentNode.parentNode;
$arr.push({
date: tr.cells[0].innerText,
activity: tr.cells[1].innerText
});
}
}
return $arr;
}
function SendData() {
var obj = {
test: CheckData()
};
var jsonString = "jsonString=" + (JSON.stringify(obj));
document.getElementById('jsonString').innerHTML = jsonString;
return; // for testing
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", "JSON_H.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form- urlencoded");
xmlhttp.setRequestHeader("Content-Length", jsonString.length);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState === 4 && (xmlhttp.status === 200)) {
alert(xmlhttp.responseText);
}
};
xmlhttp.send(jsonString);
}
table,
td {
border: 1px solid black;
padding: 0 40px 0 40px;
}
tr {
background-color: #00FF00;
}
.Green {
background-color: #00FF00;
}
.Red {
background-color: #FF0000;
}
<form>
Date:
<input type="text" id="Datum" name="Date">Activ:
<input type="text" id="Activity" name="Activ">Time:
<input type="text" id="time" name="Time">
</form>
<button onclick="AddRow()">Add Data!</button>
<table id="myTable">
<tr>
<td>Date</td>
<td>Activity</td>
<td>Time</td>
<td>Done?</td>
</tr>
</table>
<button id="buttonforsend" onclick="SendData()">Send greenmarked data!</button>
<pre id="jsonString"></pre>
Since, id of an element must be unique, the id attribute of checkbox is changed to class