I am trying to add data dynamically in table from array object, and also I need to add serial number and icons (approve and reject) in action column. But right now am only able to add employee names for array object. How to add serial number and icons in column in this table. plz check image.
https://i.stack.imgur.com/sJDWK.png
Javascript -
const button = document.getElementById('btn2');
const employee = [
{
name:'shubham',
company:'google'
},
{
name:'yash',
company:'facebook'
},
{
name:'saurabh',
company:'hcl'
}
]
const mydiv = document.getElementById('mydiv');
employee.forEach(event =>{
const td = document.createElement('td');
const tr = document.createElement('tr');
tr.appendChild(td);
mydiv.appendChild(tr);
td.innerHTML = event.name
})
button.addEventListener('click', () =>{
const username = document.getElementById('username');
const userpass = document.getElementById('userpass');
if((username.value == "admin" && userpass.value == "admin") && (username.value != "" && userpass.value != "")){
console.log('yes')
window.location.pathname = 'dashboard.html';
}
})
HTML -
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" >
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="container">
<h2>Welcome</h2>
<div >
<table class="table table-bordered" id="mydiv">
<tr>
<th>Sr.No.</th>
<th>Employee Name</th>
<th>Action</th>
</tr>
</table>
</div>
</div>
<script type="text/javascript" src="function.js"></script>
</body>
</html>
You can try something like this:
const employee = [
{
name:'shubham',
company:'google',
action: 'some action'
},
{
name:'yash',
company:'facebook',
action: 'some action'
},
{
name:'saurabh',
company:'hcl',
action: 'some action'
}
]
const mydiv = document.getElementById('mydiv');
employee.forEach((event, key) =>{
const serialTd = document.createElement('td');
const nameTd = document.createElement('td');
const actionTd = document.createElement('td');
const tr = document.createElement('tr');
tr.appendChild(serialTd);
tr.appendChild(nameTd);
tr.appendChild(actionTd);
mydiv.appendChild(tr);
nameTd.innerHTML = event.name
serialTD.innerHTML = key
actionTd.innerHTML = event.action
})
Related
I followed the below code to make a normal table into data table.. i included all the links responsible to make data table.. but still data table is not showing up.. pls resolve the error anyone?
<!DOCTYPE html>
<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>ASSESSMENT 2</title>
<link rel="stylesheet" href="style.css">
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script src="https://cdn.datatables.net/1.12.1/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.12.1/js/dataTables.bootstrap4.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.2/css/bootstrap.css">
<link rel="stylesheet" href="https://cdn.datatables.net/1.12.1/css/dataTables.bootstrap4.min.css">
<script>
$(document).ready(function () {
$('#example').DataTable();
});
</script>
</head>
<body>
<div id="" class="container">
<!-- <button type="button" onclick="run()"> Click Me </button> -->
<h1 class="text-center">Table of Data</h1>
<!--id="example" -->
<table id="example" class="table ">
<tr>
<th>NO</th>
<th>API</th>
<th>Description</th>
</tr>
</table>
</div>
<script>
const table = document.getElementById("example")
function run() {
var xhr = new XMLHttpRequest();
var url = 'https://api.publicapis.org/entries';
xhr.open("GET", url, true);
xhr.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
// getting res and to convert in json
let res = this.responseText;
let data = JSON.parse(res);
// console.log(data);
//traverse data
let NO =[]
let API = []
let Description = []
for (let i = 0; i < 100; i++) {
NO.push([i]);
API.push(data["entries"][i]["API"])
Description.push(data["entries"][i]["Description"])
}
// to create a table
for (let i = 0; i < 100; i++) {
let row = table.insertRow(i + 1);
//add cells
let cell0 = row.insertCell(0);
let cell1 = row.insertCell(1);
let cell2 = row.insertCell(2);
// to insert the data
cell0.innerHTML = NO [i]
cell1.innerHTML = API[i];
cell2.innerHTML = Description[i];
}
}
}
xhr.send();
}
run()
</script>
</body>
</html>
shall i need to put some specific links are the above things is enough? the output shows a normal table.. i have also called the table's id in script tag also.. is anything need to be done
{
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を追加
const todo = {
task: 'taskSpanTd',
status: '作業中'
};
todos.push(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);
};
//Perform processing to add td element when clicking the add button
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);
//When you press the button, it changes from working to completion
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*/
}
});
})
/*Processing when pressing the radio button in progress*/
radioDone.addEventListener('click', function () {
let workTasks = document.getElementsByClassName('work');
workTasks = Array.from(workTasks);
if (radioWork.checked === true) {
workTasks.forEach(function (workTasks) {
workTasks.style.display = "none";
})
} else {
workTasks.forEach(function (workTasks) {
workTasks.style.display = "none";
})
}
})
//Processing when radio button complete is pressed
radioWork.addEventListener('click', function () {
let doneTasks = document.getElementsByClassName('workDone');
doneTasks = Array.from(doneTasks);
if (radioDone.checked === true) {
doneTasks.forEach(function (doneTasks) {
doneTasks.style.display = "none";
})
} else {
doneTasks.forEach(function (doneTasks) {
doneTasks.style.display = "none";
})
}
})
// Serial number reassignment
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>
I am creating a Todo list and trying to implement it with the following contents.
https://gyazo.com/0b47106078622a1e44e912f56b5e9603
-Show/hide depending on task status
-Toggle task display depending on radio button selected
-If you add a new task when "Working" is selected, the task will be displayed
-If you add a new task when "Complete" is selected, the task will not be displayed (but it is added correctly in the background)
■ Current problems
(1) If you press the task completion button and then put the check box into operation, "Only the completion button" will be hidden.
→I want to hide every td
(2) Even if you click the in-process button and then click the completion check box, it will not be hidden
■ Tried
if (createButton.textContent === "Working") {
createButton.textContent = "Done";
const doneParent = a.target.parentNode;
doneParent.className ='workDone'; /* Done class */
Here is this.parentNode;
I changed it to
If you have any other problems, please let me know.
Thank you for your guidance.
Excuse the question.
I want to make a todo list like this.
https://gyazo.com/0dd4feeea3f7a27aefe6d2160944c65e
However, when I press the "Add button", the task goes to the right instead of going down.
In such cases, how should I implement it?
※As a condition, I want to separate addTask function and addButton function.
{
document.addEventListener('DOMContentLoaded', function() {
const addTaskTrigger = document.getElementsByClassName('addTask-trigger')[0];
const addTaskTarget = document.getElementsByClassName('addTask-target')[0];
const addTaskValue = document.getElementsByClassName('addTask-value')[0];
let nextId = 0;
const todos = [];
var tableItem = document.createElement('tr');
const addTask = (task, id) => {
let idSpanTd = document.createElement('td');
let taskSpanTd = document.createElement('td');
//要素内のHTML文章を変更する
idSpanTd.innerText = id;
taskSpanTd.innerText = task;
//生成したテーブル要素をブラウザに表示する
tableItem.append(idSpanTd);
tableItem.append(taskSpanTd);
addTaskTarget.append(tableItem);
return(task,id)
};
//Button要素を生成する
let removeButton = document.createElement('button');
let createButton = document.createElement('button');
const addButton = (button) => {
let createButtonTd = document.createElement('td');
let 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);
return(button)
};
//追加ボタンをクリックした際にタスクを追加する処理を行う
addTaskTrigger.addEventListener('click', () => {
const task = addTaskValue.value;
addTask(task, nextId++);
addButton();
addTaskValue.value = '';
});
//チェックリスト用オブジェクト
const todo = {
task: 'taskSpanTd',
status: '作業中'
};
todos.push(todo);
removeButton.addEventListener('click', delete_element, false);
// //削除ボタンを押した時にタスクを削除する
function delete_element () {
let tabletag = this.closest ('tr');
if (tabletag)
tabletag.remove ();
}
});
}
<!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="status" value="1" checked="checked">全て
<input type="radio" name="status" value="2">作業中
<input type="radio" name="status" value="3">完了
</p>
<p></p>
<table>
<thead>
<th>ID</th>
<th>コメント</th>
<th>状態</th>
<th></th>
</thead>
<tbody class ="addTask-target"></tbody>
</table>
<h2>新規タスクの追加</h2>
<input class="addTask-value" type="text" />
<button class="addTask-trigger" type="button">追加</button>
<script src="js/main.js"></script>
</body>
</script>
</html>
You have defined only one tableItem, only one removeButton and only one createButton.
You must define tableItem, removeButton and createButton as void variables, and only give them a value inside the addTaskTrigger.addEventListener('click') function. It would look like this:
addTaskTrigger.addEventListener('click', () => {
const task = addTaskValue.value;
// Must be already defined as variables
tableItem = document.createElement('tr');
removeButton = document.createElement('button');
createButton = document.createElement('button');
addTask(task, nextId++);
addButton();
addTaskValue.value = '';
});
You are defining only one event listener for each button (remove and create), but won't be enough for javascript to understand that it must listen to all of the rows' buttons. To do it the way you want, you must also define the eventListener only when the user adds a new task (you could define it inside the addButton() function, using the buttons IDs)
Just move creating elements (tableItem, removeButton, createButton, etc.) to the click handler.
{
document.addEventListener('DOMContentLoaded', function() {
const addTaskTrigger = document.getElementsByClassName('addTask-trigger')[0];
const addTaskTarget = document.getElementsByClassName('addTask-target')[0];
const addTaskValue = document.getElementsByClassName('addTask-value')[0];
let nextId = 0;
const todos = [];
const addTask = (task, id, tableItem) => {
let idSpanTd = document.createElement('td');
let taskSpanTd = document.createElement('td');
//要素内のHTML文章を変更する
idSpanTd.innerText = id;
taskSpanTd.innerText = task;
//生成したテーブル要素をブラウザに表示する
tableItem.append(idSpanTd);
tableItem.append(taskSpanTd);
addTaskTarget.append(tableItem);
return(task,id)
};
//Button要素を生成する
const addButton = (tableItem, removeButton, createButton) => {
let createButtonTd = document.createElement('td');
let 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);
};
//追加ボタンをクリックした際にタスクを追加する処理を行う
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 = '';
removeButton.addEventListener('click', delete_element, false);
});
//チェックリスト用オブジェクト
const todo = {
task: 'taskSpanTd',
status: '作業中'
};
todos.push(todo);
// //削除ボタンを押した時にタスクを削除する
function delete_element () {
let tabletag = this.closest ('tr');
if (tabletag)
tabletag.remove ();
}
});
}
<!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="status" value="1" checked="checked">全て
<input type="radio" name="status" value="2">作業中
<input type="radio" name="status" value="3">完了
</p>
<p></p>
<table>
<thead>
<th>ID</th>
<th>コメント</th>
<th>状態</th>
<th></th>
</thead>
<tbody class ="addTask-target"></tbody>
</table>
<h2>新規タスクの追加</h2>
<input class="addTask-value" type="text" />
<button class="addTask-trigger" type="button">追加</button>
<script src="js/main.js"></script>
</body>
</script>
</html>
I want to use the specifications shown in this video, but it does not work.
Please confirm it.
https://gyazo.com/0dd4feeea3f7a27aefe6d2160944c65e
Conditions:
You can delete the task when you press the delete button
ID is reassigned when deleting a task
After deleting, when adding a new task, the IDs are serialized
<!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="status" value="1" checked="checked">全て
<input type="radio" name="status" value="2">作業中
<input type="radio" name="status" value="3">完了
</p>
<p></p>
<table>
<thead>
<th>ID</th>
<th>コメント</th>
<th>状態</th>
<th></th>
</thead>
<tbody class ="addTask-target"></tbody>
</table>
<h2>新規タスクの追加</h2>
<input class="addTask-value" type="text" />
<button class="addTask-trigger" type="button">追加</button>
<script src="js/main.js"></script>
</body>
</script>
</html>
document.addEventListener('DOMContentLoaded', function() {
const addTaskTrigger = document.getElementsByClassName('addTask-trigger')[0];
const addTaskTarget = document.getElementsByClassName('addTask-target')[0];
const addTaskValue = document.getElementsByClassName('addTask-value')[0];
let nextId = 0;
const todos = [];
const addTask = (task,id) => {
//テーブル要素を生成する td要素を作る
const tableItem = document.createElement('tr');
const addButtonTd = document.createElement('td');
const idSpanTd = document.createElement('td');
const taskSpanTd = document.createElement('td');
const removeButtonTd = document.createElement('td');
//Button要素を生成する
const addButton = document.createElement('button')
const removeButton = document.createElement('button')
//要素内のHTML文章を変更する
addButton.innerText = '作業中';
removeButton.innerText = '削除';
idSpanTd.innerText = id;
taskSpanTd.innerText = task;
//生成したテーブル要素をブラウザに表示する
tableItem.append(idSpanTd);
tableItem.append(taskSpanTd);
tableItem.append(addButtonTd);
tableItem.append(removeButtonTd);
addTaskTarget.appendChild(tableItem);
//生成したbutton要素を生成する
addButtonTd.append(addButton);
removeButtonTd.append(removeButton);
const todo = {
task: 'taskSpanTd',
status: '作業中'
};
todos.push(todo);
};
addTaskTrigger.addEventListener('click',() => {
const task = addTaskValue.value;
addTask(task,nextId ++);
addTaskValue.value = '';
});
const element = document.querySelector('td')
document.getElementById("removebutton").onclick = function() {
element.remove();
};
});
Define your buttons click actions upon buttons creation
Use Object.defineProperty() to handle your todo "status" property and reactively apply changes to the TR element classList
Use String.prototype.trim() - you don'w want empty spaces to become new todo tasks.
preferably use always Element.textContent instead of Element.innerText
When deleting your TR element, don't forget to update the todos Array by removing that item using todos.splice(todos.indexOf(todo), 1);
// Helper functions
const ELNew = (sel, attr) => Object.assign(document.createElement(sel), attr || {});
const EL = (sel, EL) => (EL || document).querySelector(sel);
// Todo App
const EL_list = EL('#todo-list');
const EL_task = EL('#todo-task');
const EL_add = EL('#todo-add');
const todos = [];
let id = 0;
const addTask = () => {
const task = EL_task.value.trim(); // Always trim!
if (!task) return; // Do nothing
EL_task.value = "";
id += 1;
const todo = {
id: id,
task: task,
status: "",
};
// Make "status" reactive
Object.defineProperty(todo, "__status", {
set(val) {
this.status = val;
TR.classList.remove("is-done", "is-doing");
TR.classList.add(`is-${this.status}`);
}
});
todos.push(todo);
// New Elements
const TR = ELNew("tr");
const TD_id = ELNew("td", {textContent: id});
const TD_task = ELNew("td", {textContent: task});
const TD_status = ELNew("td");
const TD_remove = ELNew("td");
const EL_btn_doing = ELNew("button", {
className: "todo-btn-doing",
textContent: "Doing",
type: "button",
onclick() {
todo.__status = "doing";
}
});
const EL_btn_done = ELNew("button", {
className: "todo-btn-done",
textContent: "Done",
type: "button",
onclick() {
todo.__status = "done";
}
});
const EL_btn_remove = ELNew("button", {
textContent: "×",
title: "Remove this task",
type: "button",
onclick() {
if (!confirm(`Remove task ID:${id} "${task}"`)) return; // Do nothing
TR.remove(); // Remove element
todos.splice(todos.indexOf(todo), 1); // Remove from todos list
}
});
// Insertions
TD_status.append(EL_btn_doing, EL_btn_done);
TD_remove.append(EL_btn_remove);
TR.append(TD_id, TD_task, TD_status, TD_remove);
EL_list.append(TR);
};
EL_add.addEventListener("click", addTask);
/*QuickReset*/* {margin:0; box-sizing:border-box;}
table {
border-collapse: collapse;
border-spacing: 0;
}
table th,
table td {
padding: 5px 10px;
}
#todo-list tr.is-doing td {
background: #fb0;
}
#todo-list tr.is-done td {
background: #0fb;
text-decoration: line-through;
}
#todo-list tr.is-doing .todo-btn-doing {
color: #fb0;
}
#todo-list tr.is-done .todo-btn-done {
color: #0fb;
}
<table>
<thead>
<th>ID</th>
<th>Description</th>
<th>Status</th>
<th></th>
</thead>
<tbody id="todo-list"></tbody>
</table>
<h2>Add new Todo</h2>
<input id="todo-task" type="text" />
<button id="todo-add" type="button">Add</button>
I am building a basic CRUD app and I am using Firebase for my backend. I have implemented the create and read functionality, but I am having problems with the delete method. The results are shown from my database in a html table and after each result there is a delete button, however when you click on the delete button, firebase gives me this error: Uncaught Error: Function CollectionReference.doc() requires its first argument to be of type non-empty string, but it was: null
Why, what am I doing wrong?
here is my js:
const animalList = document.querySelector('#animal-list');
const form = document.querySelector('#add-animals');
function renderAnimals(doc) {
let tr = document.createElement('tr');
let td = document.createElement('td');
let deleteButton = document.createElement('button');
let editButton = document.createElement('button')
// Animal properties
let name = document.createElement('div');
let species = document.createElement('div');
let age = document.createElement('div');
let last_fed = document.createElement('div');
let last_shed = document.createElement('div');
let diet = document.createElement('div');
let basking_area_temp = document.createElement('div');
let cold_part_temp = document.createElement('div');
let humidity = document.createElement('div');
let additional_info = document.createElement('div');
// Edit Form inputs and buttons
let editForm = document.createElement('form');
let submit = document.createElement('input');
let nameInput = document.createElement('input');
let speciesInput = document.createElement('input');
let ageSpecies = document.createElement('input');
let lastFedInput = document.createElement('input');
let lastShedInput = document.createElement('input');
let dietInput = document.createElement('input');
let baskingAreaTempInput = document.createElement('input');
let coldPartTempInput = document.createElement('input');
let humidityInput = document.createElement('input');
let additionalInfoInput = document.createElement('input');
// Edit modal creation
let modal = document.createElement('div');
let modalDialog = document.createElement('div');
let modalContent = document.createElement('div');
let span = document.createElement('span');
let h2 = document.createElement('h2');
let nameLabel = document.createElement('label');
let speciesLabel = document.createElement('label');
let ageLabel = document.createElement('label');
let lastFedLabel = document.createElement('label');
let lastShedLabel = document.createElement('label');
let dietLabel = document.createElement('label');
let baskingAreaTempLabel = document.createElement('label');
let coldPartTempLabel = document.createElement('label');
let humidityLabel = document.createElement('label');
let additionalInfoLabel = document.createElement('label');
// Class and data setting
tr.setAttribute('data-id', doc.id);
name.textContent = `name: ${doc.data().name}`;
deleteButton.textContent = 'Delete';
deleteButton.setAttribute('class','btn btn-danger');
editButton.textContent = 'Edit';
editButton.setAttribute('class', 'btn btn-info');
editForm.setAttribute('class', 'form-group');
modal.setAttribute('id','editModal');
modal.setAttribute('class','modal ');
modal.setAttribute('tabindex', '-1');
modalDialog.setAttribute('class', 'modal-dialog');
modalContent.setAttribute('class','modal-content container');
span.textContent = 'X';
span.setAttribute('class','close');
h2.textContent = 'Edit Animal';
speciesLabel.innerHTML = 'Species:';
nameLabel.innerHTML = 'Name:';
ageLabel.textContent = 'Age:';
lastFedLabel.textContent='Last Fed:';
lastShedLabel.textContent= 'Last Shed:';
dietLabel.textContent = 'Diet:';
baskingAreaTempLabel.textContent = 'Basking temps';
coldPartTempLabel.textContent = 'Cold Part Temps';
humidityLabel.textContent = 'Humidity';
additionalInfoInput.textContent = 'Additional Info';
species.textContent = `species: ${doc.data().species}`;
age.textContent = `age: ${doc.data().age}`;
last_fed.textContent = `last fed: ${doc.data().last_fed}`;
last_shed.textContent = `last shed: ${doc.data().last_shed}`;
diet.textContent = `diet: ${doc.data().diet}`;
basking_area_temp.textContent =`basking area temp: ${ doc.data().basking_area_temp}`;
cold_part_temp.textContent = `cold part temp: ${doc.data().cold_part_temp}`;
humidity.textContent = `humidity: ${doc.data().humidity}`;
additional_info.textContent = `additional info: ${doc.data().additional_info}`;
editForm.setAttribute('method',"post");
editForm.setAttribute('action',"#");
editForm.setAttribute('class','edit-form');
submit.setAttribute('type',"submit");
submit.setAttribute('value',"Update");
submit.setAttribute('class',"btn btn-success");
nameLabel.setAttribute('for','name');
speciesLabel.setAttribute('for','name');
ageLabel.setAttribute('for','name');
lastFedLabel.setAttribute('for','');
lastShedLabel.setAttribute('for','last shed');
dietLabel.setAttribute('for','diet');
nameInput.setAttribute('class','form-control')
speciesInput.setAttribute('class','form-control');
ageSpecies.setAttribute('class','form-control');
lastFedInput.setAttribute('class','form-control');
lastShedInput.setAttribute('class','form-control');
baskingAreaTempInput.setAttribute('class','form-control');
coldPartTempInput.setAttribute('class','form-control');
humidityInput.setAttribute('class','form-control');
additionalInfoInput.setAttribute('class','form-control');
speciesInput.setAttribute('class','form-control');
dietInput.setAttribute('class','form-control');
//Visualizing the table
td.appendChild(species);
td.append(age);
td.append(last_fed);
td.append(last_shed);
td.append(diet);
td.append(basking_area_temp);
td.append(cold_part_temp);
td.append(humidity);
td.append(additional_info);
td.append(deleteButton);
td.append(editButton);
td.appendChild(nameInput);
td.append(ageSpecies);
td.append(lastFedInput);
td.append(lastShedInput);
td.append(dietInput);
td.append(baskingAreaTempInput);
td.append(coldPartTempInput);
td.append(humidityInput);
// td.append(additionalInfoInput);
td.append(speciesInput);
tr.appendChild(td);
editForm.append(nameLabel);
editForm.appendChild(nameInput);
editForm.append(ageLabel);
editForm.append(ageSpecies);
editForm.append(lastFedLabel);
editForm.append(lastFedInput);
editForm.append(lastShedLabel);
editForm.append(lastShedInput);
editForm.append(dietLabel);
editForm.append(dietInput);
editForm.append(baskingAreaTempLabel);
editForm.append(baskingAreaTempInput);
editForm.append(coldPartTempLabel);
editForm.append(coldPartTempInput);
editForm.append(humidityLabel);
editForm.append(humidityInput);
editForm.append(additionalInfoLabel);
// editForm.append(additionalInfoInput);
editForm.append(speciesLabel);
editForm.append(speciesInput);
editForm.append(submit);
td.append(editForm);
tr.appendChild(td);
modal.append(modalDialog);
modalDialog.append(modalContent);
modalContent.append(span);
modalContent.append(h2);
td.append(modal);
modalContent.append(editForm);
animalList.appendChild(tr);
// Firebase operations
//deleting data
deleteButton.addEventListener('click', (event) => {
event.stopPropagation();
let id = event.target.parentElement.getAttribute('data-id');
db.collection('animals').doc(id).delete();
})
editButton.addEventListener('click', () => {
modal.style.display = 'flex';
})
span.addEventListener('click', () => {
modal.style.display = "none";
})
}
// getting data from the back end
db.collection('animals').onSnapshot(snapshot => {
let changes = snapshot.docChanges();
changes.forEach(change => {
if(change.type == 'added') {
renderAnimals(change.doc);
} else if (change.type == 'removed') {
let li = animalList.querySelector('[data-id=' + change.doc.id + ']');
animalList.removeChild(li);
}
})
})
// adding data
form.addEventListener('submit', (event) => {
event.preventDefault();
db.collection('animals').add({
species: form.species.value,
name: form.name.value,
age: form.age.value,
last_fed: document.querySelector('#last-fed').value,
last_shed: document.querySelector('#last-shed').value,
diet: form.diet.value,
basking_area_temp: document.querySelector('#basking-area-temperature').value,
cold_part_temp: document.querySelector('#cold-temperature').value,
humidity: form.humidity.value,
additional_info: document.querySelector('#additional-info').value
})
})
and my html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Repti Care</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://www.gstatic.com/firebasejs/5.5.7/firebase.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.5.5/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.5.5/firebase-firestore.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css"
integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
<link rel="stylesheet" href="./css/main.css">
</head>
<body>
<div class="jumbotron">
<div class="placeholder"></div>
</div>
<div class="container">
<h2>Add a new Animal</h2>
<form class="form-group" id="add-animals">
Species: <input type="text" id="species" class="form-control">
Name: <input type="text" id="name" class="form-control" >
Age: <input type="text" id="age" class="form-control">
Last Fed: <input type="date" id="last-fed" class="form-control">
Last Shed: <input type="date" id="last-shed" class="form-control">
Diet: <input type="text" id="diet" class="form-control">
Basking area temperature: <input type="text" id="basking-area-temperature" class="form-control">
Cold part temperature: <input type="text" id="cold-temperature" class="form-control">
Humidity: <input type="text" id="humidity" class="form-control">
Addition Info: <textarea class="form-control" id="additional-info"></textarea>
<button id="btnCreate" class="btn btn-primary">Create</button>
</form>
<h3>View Current Animals</h3>
<table id="animal-list">
<th>Animals</th>
</table>
</div>
</div>
<script>
// Initialize Firebase
var config = {
apiKey: "AIzaSyBSuC8nqJzLe7d5jKS-_nE15kaI9Y6NIfI",
authDomain: "repti-care-32176.firebaseapp.com",
databaseURL: "https://repti-care-32176.firebaseio.com",
projectId: "repti-care-32176",
storageBucket: "repti-care-32176.appspot.com",
messagingSenderId: "632910932105"
};
firebase.initializeApp(config);
const db = firebase.firestore();
db.settings({ timestampsInSnapshots: true });
</script>
<script
src="https://code.jquery.com/jquery-3.3.1.js"
integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="
crossorigin="anonymous"></script>
<script src="./scripts/main.js"></script>
</body>
</html>
I tried looking up the error and reading firebase documentation but I could not find anything.
The immediate problem is that you attempt to set the data-id property on a <tr> element, but try to read it from a <td> element inside that <tr>. See:
tr.setAttribute('data-id', doc.id);
...
td.append(deleteButton);
...
tr.appendChild(td);
...
let id = event.target.parentElement.getAttribute('data-id');
So the parent will not be your tr but the directly enclosing td.
The error message is telling you that you passed an invalid value to the doc() method here:
db.collection('animals').doc(id).delete();
You need to debug your code and figure out why id is null or undefined.