button functionality for selected items JS - javascript

I am doing To Do List app. After the user-input, information is displayed in the table. My goal is to mark the selected item from that table and apply some button functionalities to them ( mark them completed, important, or remove the item). However, I figured out the selecting part, but can not make the button work.
here is the printscreen
!(https://ibb.co/dtZ11KD)
HTML
<strike>
<form>
<div>
<label for="todo-date">Date</label>
<input type="date" class="todo-date" id="todo-date">
</div>
<div>
<label for="todo-task">Task</label>
<input type="text" class="todo-input" id="todo-task">
</div>
<div>
<label for="todo-responsible">Who is responsible</label>
<input type="text" class="todo-responsible" id="todo-responsible">
</div>
<div>
<button class="todo-button" id="todo-button">
<i class="fas fa-plus-square"></i>
</button>
</div>
</form>
<table class="content-table" id="content-table">
<thead>
<tr>
<th>Date</th>
<th>Task</th>
<th>Responsible</th>
</tr>
</thead>
<tbody id="tbl-result" class="tblResult">
<tr class="tbr-click">
<td>Date</td>
<td>Task</td>
<td>Responsible</td>
</tr>
</tbody>
</table>
<section>
<div>
<button class="complete-btn" id="complete-btn">
<i class="fas fa-check"></i>
</button>
</div>
<div>
<button class="imp-btn" id="imp-btn">
<i class="fas fa-trash"></i>
</button>
</div>
<div>
<button class="trash-btn" id="trash-btn">
<i class="fas fa-exclamation"></i>
</button>
</div>
</section>
<script src="app.js"></script>
</body>
</html>
</strike>
'''
// Selectors
const toDoDate = document.getElementById('todo-date');
const toDoInput = document.getElementById('todo-task');
const toDoResp = document.getElementById('todo-responsible');
const toDoButton = document.getElementById('todo-button');
const completeBtn = document.getElementById('complete-btn');
const impBtn = document.getElementById('imp-btn');
const trashBtn = document.getElementById('trash-btn');
const tblResult = document.getElementById('tbl-result');
const cntTable = document.getElementById('content-table');
const cntCells = document.getElementsByTagName('td');
// Event listeners
toDoButton.addEventListener('click', addToDo);
completeBtn.addEventListener('click', addComplete);
impBtn.addEventListener('click', markImp);
trashBtn.addEventListener('click', deletBtn);
// Functions
function addToDo(event) {
event.preventDefault();
let newRow = tblResult.insertRow(0);
let cell1 = newRow.insertCell(0);
let cell2 = newRow.insertCell(1);
let cell3 = newRow.insertCell(2);
cell1.innerHTML = toDoDate.value;
cell2.innerHTML = toDoInput.value;
cell3.innerHTML = toDoResp.value;
selectRow();
}
function selectRow () {
for (i=0; i < cntCells.length; i++) {
cntCells[i].onclick = function () {
let indexSel = this.parentNode.rowIndex;
let rowsNotSelected = cntTable.getElementsByTagName('tr');
for (let row = 0; row < rowsNotSelected.length; row++) {
rowsNotSelected[row].style.backgroundColor = "";
rowsNotSelected[row].classList.remove('selected');
}
let rowSelected = cntTable.getElementsByTagName('tr')[indexSel];
rowSelected.style.backgroundColor = "yellow";
rowSelected.classList.add('selected');
}
}
}
function addComplete () {
if (rowSelected.classList.contains('selected')) {
console.log('hey');
} else {
console.log('no');
}
}
function markImp () {
console.log('Mark');
}
function deletBtn () {
console.log('DELETE');
}
'''
Buttons are working, the function addCompleted is not. Any kind of help or advice would help.

Make your rowSelected global for general access.. Modify as below
let rowSelected;
function selectRow () {
for (i=0; i < cntCells.length; i++) {
cntCells[i].onclick = function () {
let indexSel = this.parentNode.rowIndex;
let rowsNotSelected = cntTable.getElementsByTagName('tr');
for (let row = 0; row < rowsNotSelected.length; row++) {
rowsNotSelected[row].style.backgroundColor = "";
rowsNotSelected[row].classList.remove('selected');
}
//do not re-declare rowSelected, just assign;
rowSelected = cntTable.getElementsByTagName('tr')[indexSel];
rowSelected.style.backgroundColor = "yellow";
rowSelected.classList.add('selected');
}
}
}

Remember when declaring a variable inside a function it's scope is inside that function. you cannot access it outside that method. Your mistake is you trying to access 'rowSelected' variable from another function which is not accessible to this variable. make this variable global one so you can access. Please refer JS variable scope.
refer this variable scopes doc
I corrected your code. please check
let rowSelected
var init = () => {
const toDoDate = document.getElementById('todo-date');
const toDoInput = document.getElementById('todo-task');
const toDoResp = document.getElementById('todo-responsible');
const toDoButton = document.getElementById('todo-button');
const completeBtn = document.getElementById('complete-btn');
const impBtn = document.getElementById('imp-btn');
const trashBtn = document.getElementById('trash-btn');
const tblResult = document.getElementById('tbl-result');
const cntTable = document.getElementById('content-table');
const cntCells = document.getElementsByTagName('td');
// Event listeners
toDoButton.addEventListener('click', addToDo);
completeBtn.addEventListener('click', addComplete);
impBtn.addEventListener('click', markImp);
trashBtn.addEventListener('click', deletBtn);
// Functions
function addToDo(event) {
event.preventDefault();
let newRow = tblResult.insertRow(0);
let cell1 = newRow.insertCell(0);
let cell2 = newRow.insertCell(1);
let cell3 = newRow.insertCell(2);
cell1.innerHTML = toDoDate.value;
cell2.innerHTML = toDoInput.value;
cell3.innerHTML = toDoResp.value;
selectRow();
}
function selectRow() {
for (i = 0; i < cntCells.length; i++) {
cntCells[i].onclick = function () {
let indexSel = this.parentNode.rowIndex;
let rowsNotSelected = cntTable.getElementsByTagName('tr');
for (let row = 0; row < rowsNotSelected.length; row++) {
rowsNotSelected[row].style.backgroundColor = "";
rowsNotSelected[row].classList.remove('selected');
}
rowSelected = cntTable.getElementsByTagName('tr')[indexSel];
rowSelected.style.backgroundColor = "yellow";
rowSelected.classList.add('selected');
}
}
}
function addComplete() {
if (rowSelected.classList.contains('selected')) {
console.log('hey');
} else {
console.log('no');
}
}
function markImp() {
console.log('Mark');
}
function deletBtn() {
console.log('DELETE');
}
}
init();
<form>
<div>
<label for="todo-date">Date</label>
<input type="date" class="todo-date" id="todo-date">
</div>
<div>
<label for="todo-task">Task</label>
<input type="text" class="todo-input" id="todo-task">
</div>
<div>
<label for="todo-responsible">Who is responsible</label>
<input type="text" class="todo-responsible" id="todo-responsible">
</div>
<div>
<button class="todo-button" id="todo-button">
<i class="fas fa-plus-square"></i>
Add todo
</button>
</div>
</form>
<table class="content-table" id="content-table">
<thead>
<tr>
<th>Date</th>
<th>Task</th>
<th>Responsible</th>
</tr>
</thead>
<tbody id="tbl-result" class="tblResult">
<tr class="tbr-click">
<td>Date</td>
<td>Task</td>
<td>Responsible</td>
</tr>
</tbody>
</table>
<section>
<div>
<button class="complete-btn" id="complete-btn">
<i class="fas fa-check"></i>
complte
</button>
</div>
<div>
<button class="imp-btn" id="imp-btn">
<i class="fas fa-trash"></i>
mark
</button>
</div>
<div>
<button class="trash-btn" id="trash-btn">
<i class="fas fa-exclamation"></i>
delete
</button>
</div>
</section>

EDIT: I changed your selectRow() function logic in order to make the process much simplier. Now it uses a real CSS class. The code is more cleaner and behavior is the same.
Just use a querySelector() since you are adding the class selected to the selected row. If none row has the selected class, then selectedRow will be null in the addComplete function. Otherwise, will be the selected row.
I also modified your delete and imp icon's button cause you mix them.
// Selectors
const toDoDate = document.getElementById('todo-date');
const toDoInput = document.getElementById('todo-task');
const toDoResp = document.getElementById('todo-responsible');
const toDoButton = document.getElementById('todo-button');
const completeBtn = document.getElementById('complete-btn');
const impBtn = document.getElementById('imp-btn');
const trashBtn = document.getElementById('trash-btn');
const tblResult = document.getElementById('tbl-result');
const cntTable = document.getElementById('content-table');
const cntCells = document.getElementsByTagName('td');
// Event listeners
toDoButton.addEventListener('click', addToDo);
completeBtn.addEventListener('click', addComplete);
impBtn.addEventListener('click', markImp);
trashBtn.addEventListener('click', deleteBtn);
// Functions
function addToDo(event) {
event.preventDefault();
let newRow = tblResult.insertRow(0);
let cell1 = newRow.insertCell(0);
let cell2 = newRow.insertCell(1);
let cell3 = newRow.insertCell(2);
cell1.innerHTML = toDoDate.value;
cell2.innerHTML = toDoInput.value;
cell3.innerHTML = toDoResp.value;
newRow.addEventListener('click', selectRow);
}
function selectRow() {
this.classList.toggle('selected');
document.querySelectorAll('.selected').forEach(item => {
if (item !== this) {
item.classList.remove('selected');
}
});
}
function addComplete() {
const rowSelected = document.querySelector('.selected');
if (rowSelected) {
console.log('hey');
} else {
console.log('no');
}
}
function markImp() {
console.log('Mark');
}
function deleteBtn() {
console.log('DELETE');
}
.selected {
background-color: yellow;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.1/css/all.min.css" rel="stylesheet"/>
<form>
<div>
<label for="todo-date">Date</label>
<input type="date" class="todo-date" id="todo-date">
</div>
<div>
<label for="todo-task">Task</label>
<input type="text" class="todo-input" id="todo-task">
</div>
<div>
<label for="todo-responsible">Who is responsible</label>
<input type="text" class="todo-responsible" id="todo-responsible">
</div>
<div>
<button class="todo-button" id="todo-button">
<i class="fas fa-plus-square"></i>
</button>
</div>
</form>
<table class="content-table" id="content-table">
<thead>
<tr>
<th>Date</th>
<th>Task</th>
<th>Responsible</th>
</tr>
</thead>
<tbody id="tbl-result" class="tblResult"></tbody>
<tfoot>
<tr>
<td>Date</td>
<td>Task</td>
<td>Responsible</td>
</tr>
</tfoot>
</table>
<section>
<div>
<button class="complete-btn" id="complete-btn">
<i class="fas fa-check"></i>
</button>
</div>
<div>
<button class="imp-btn" id="imp-btn">
<i class="fas fa-exclamation"></i>
</button>
</div>
<div>
<button class="trash-btn" id="trash-btn">
<i class="fas fa-trash"></i>
</button>
</div>
</section>

Related

JavaScript plain CRUD edit function - update/ edit the input fields in the table

I need help by the implementation for a edit/update function. My goal is to edit/update the input fields from the customer. Thanks in advance! I tried to code the implementation into the function editFields(). Whenever the customer clicked the button "edit", he can edit/update the text fields from the table (please see picture).
HTML:
<!--CONTENT-->
<div class="content">
<!--CONTENT-PAGE-->
<div class="content__page">
<!--CAR-FORM-->
<div class="content__page__carForm">
<form id="car-form">
<label for="producer">Producer</label>
<input type="text" id="producer" class="form-controll">
<label for="model">Model</label>
<input type="text" id="model" class="form-controll">
<label for="color">Color</label>
<input type="text" id="color" class="form-controll">
<label for="price">Price</label>
<input type="text" id="price" class="form-controll">
<input type="submit" id="submit--button" value="Add Car" class="btn btn-primary btn-block">
</form>
<!--CAR-TABLE-->
<table class="table table-striped" id="car-table">
<thead>
<tr>
<th>Producer</th>
<th>Model</th>
<th>Color</th>
<th>Price</th>
</tr>
</thead>
</table>
</div>
</div>
</div>
JS:
class Car {
constructor(producer, model, color, price) {
this.producer = producer;
this.model = model;
this.color = color;
this.price = price;
}
}
class CarList {
static addCarToList(car) {
const list = document.getElementById('car-table');
const row = document.createElement('tr');
row.innerHTML = `
<td>${car.producer}</td>
<td>${car.model}</td>
<td>${car.color}</td>
<td>${car.price}</td>
<td>X</td>
<td>Edit</td>
`;
list.appendChild(row);
CarBase.addCar();
CarBase.removeCar();
}
static deleteCar(el) {
if (el.classList.contains('delete')) {
el.parentElement.parentElement.remove();
}
}
static clearFields() {
document.getElementById('producer').value = '';
document.getElementById('model').value = '';
document.getElementById('color').value = '';
document.getElementById('price').value = '';
}
static showAlert() {
}
static editFields() {
}
}
lass CarBase {
static addCar() {
document.getElementById('car-form').addEventListener('submit', (e) => {
e.preventDefault();
const producer = document.getElementById('producer').value;
const model = document.getElementById('model').value;
const color = document.getElementById('color').value;
const price = document.getElementById('price').value;
if (producer === '' || model === '' || color === '' || price === '') {
alert('Please fill out all fields');
} else {
const car = new Car(producer, model, color, price);
CarList.addCarToList(car);
CarList.clearFields();
}
});
}
static removeCar() {
document.getElementById('car-table').addEventListener('click', (e) => {
CarList.deleteCar(e.target);
CarList.showAlert();
});
}
}
const car1 = new Car('BMW', 'E63', 'Green', 15, 000);
CarList.addCarToList(car1);

Make a table row editable on click with Javascript

I want to make the row of my list editable after clicking on edit button. I set editablecontent= true for every row I want to change and added focus with onclick event but this works only for the first item. Could you suggest other ways of making the content of every row editable? I started recently to learn javascript so vanilla javascript would be better. Thanks!
Storedcontact = []
// Represent a contact
function convertToEntry(name, surname, phone, email) {
var obj = {
name: name,
surname: surname,
phone: phone,
email: email
};
return obj;
}
// add contacts
var form = document.getElementById("btn-submit");
form.addEventListener("click", function(ev) {
ev.preventDefault();
var name = document.getElementById("name").value;
var surname = document.getElementById("surname").value;
var number = document.getElementById("phone").value;
var mail = document.getElementById("email").value;
var duplicateFlag = false;
var entry = convertToEntry(name, surname, number, mail);
for (var i = 0; i < Storedcontact.length; i++) {
let entry = Storedcontact[i];
// this is duplicate
if (entry.name === name) {
alert("Duplicate") ;
duplicateFlag = true;
} else {
duplicateFlag = false;
}
}
// store and update ui onlz if name is not duplicate
if (duplicateFlag === false) {
Storedcontact.push(entry);
updateUI();
}
});
// showing contacts
function updateUI() {
var tbody = document.getElementById('entry-table');
// clearing the table
tbody.innerHTML = '';
var newHtml = '';
// looping the stored contacts
for (var i = 0; i < Storedcontact.length; i++) {
var entry = Storedcontact[i];
// printing loop results
//console.log(JSON.stringify(entry));
// creating rows with entry
var row = document.createElement("tr");
row.innerHTML = `
<td contenteditable="true" id="editable">${entry.name}</td>
<td contenteditable="true" id="editable">${entry.surname}</td>
<td contenteditable="true" id="editable">${entry.phone}</td>
<td contenteditable="true" id="editable">${entry.email}</td>
<td><button class="btn btn-danger btn-sm delete" onClick="document.getElementById('entry-table').deleteRow(${i});">Delete</button></td>
<td><button class="btn btn-danger btn-sm edit" onClick="editHtmlTableRow();">Edit</button></td>
`;
tbody.appendChild(row);
function clearFields() {
document.getElementById("name").value = "";
document.getElementById("surname").value = "";
document.getElementById("phone").value = "";
document.getElementById("email").value = "";
}
clearFields();
}
}
function checkDuplicate (name) {
for (var i = 0; i < Storedcontact.length; i++) {
var entry = Storedcontact[i];
if (entry.name === name) {
alert("Duplicate")
} else {
}
}
}
function editHtmlTableRow (){
document.getElementById("editable").focus();
};
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width-device-width, initial-scale=1.0">
<link rel="stylesheet" href="bootstrap.min (3).css">
<title>MyAddressBook</title>
</head>
<body>
<div class="container mt-4">
<h1 class="display-4 text-center">
My<span class="text-primary">Address</span>Book</h1>
<form id="address-form">
<div class="form-group"></div>
<label for="Name">Name</label>
<input type="text" id="name" class="form-control">
<div class="form-group"></div>
<label for="Surname">Surname</label>
<input type="text" id="surname" class="form-control">
<div class="form-group"></div>
<label for="Number">Number</label>
<input type="text" id="phone" class="form-control">
<div class="form-group"></div>
<label for="mail">E-mail</label>
<input type="text" id="email" class="form-control">
</div>
<br>
</br>
<input type="submit" value="Add contact" id="btn-submit" class="btn btn-primary btn-block container mt-4">
</form>
<table class="table table-striped">
<thread>
<tr>
<th>Name</th>
<th>Surname</th>
<th>Number</th>
<th>E-mail</th>
<th></th>
</tr>
</thread>
<tbody id="entry-table"></tbody>
</table>
</div>
<script src="app.js"></script>
</body>
</html>
Assign a unique identifier such as your for loop counter to the Rows
for (var i = 0; i < Storedcontact.length; i++) {
var entry = Storedcontact[i];
// printing loop results
//console.log(JSON.stringify(entry));
// creating rows with entry
var row = document.createElement("tr");
row.innerHTML = `
<td contenteditable="true" id="editable"+i>${entry.name}</td>
<td contenteditable="true" id="editable"+i>${entry.surname}</td>
<td contenteditable="true" id="editable"+i>${entry.phone}</td>
<td contenteditable="true" id="editable"+i>${entry.email}</td>
<td><button class="btn btn-danger btn-sm delete" onClick="document.getElementById('entry-table').deleteRow(${i});">Delete</button></td>
<td><button class="btn btn-danger btn-sm edit" onClick="editHtmlTableRow(${i});">Edit</button></td>
`;
tbody.appendChild(row);
}
and in your function
function editHtmlTableRow (i){
document.getElementById("editable"+i).focus();
}

Adding buttons to each row of a table to remove said row

just looking for a simple solution on solving this, Consider the the following code:
<!DOCTYPE html>
<html>
<head>
<title>Javascript - Add HTML Table Row </title>
<meta charset="windows-1252">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<form>
<script>
function addRow()
{
// get input values
var name = document.getElementById('name').value;
var currentAge =
document.getElementById('currentAge').value;
var Birthday = document.getElementById('Birthday').value;
var carType = document.getElementById('carType').value;
var Delete = document.getElementById('Delete').value;
var table = document.getElementsByTagName('table')[0];
var newRow = table.insertRow(table.rows.length/2+1);
var cel1 = newRow.insertCell(0);
var cel2 = newRow.insertCell(1);
var cel3 = newRow.insertCell(2);
var cel4 = newRow.insertCell(3);
var cel5 = newRow.insertCell(4);
cel1.innerHTML = name;
cel2.innerHTML = currentAge;
cel3.innerHTML = Birthday;
cel4.innerHTML = carType;
cel5.innerHTML = Delete;
function myFunction(){
var x = document.getElementById("table").rows.length;
document.getElementById("demo").innerHTML = "Found " + x + " tr
elements in the table.";
}
</script>
</form>
</head>
<style>
table, th {
border: 1px solid black;
}
tbody td{
padding: 30px;
}
tbody tr:nth-child(odd){
background-color: #F4BC01;
color: #ABC412;
}
$("")
</style>
<body>
<h2>Basic HTML table</h2> <button onclick="myFunction()">Press me for
elements amount</button>
<p id ="demo"></p>
Name: <input type="text" name="name" id="name" /><br/><br/>
Age: <input type="text" name="currentAge" id="currentAge" /><br/><br/>
Date of Birth <input type="date" name="Birthday" id="Birthday" /><br/>
<button onclick="addRow();">Display</button><br/><br/>
<p>Eye Colour:</p>
<select id="carType">
<option value="ferrari" id="ferrari">Ferrari</option>
<option value="lamborghini" id="lamborghini">Lamborghini</option>
<option value="porsche" id="porsche">Porsche</option>
<option value="bugatti" id="bugatti">Bugatti</option>
<option value="pagani" id="pagani">Pagani</option>
</select>
<table border="1" id="table">
<tr>
<th>Name</th>
<th>Age</th>
<th>Birthday</th>
<th>CarType</th>
<th>Delete Entry
<button id="Delete" onclick="remove_update(event)">delete</button> //this button right here but in each row and not here. should remove said row
</th>
</tr>
</table>
</body>
</html>
What im trying to do is within cel 5 (delete entry) is to add a delete button to each row that is entered into the table that will remove that row but don't know how to go about this. Ideally would like to do this without the use of JQuery if possible, since i've not touched upon it as of yet.
You can use the rowIndex property to delete the row.
function addRow() {
// get input values
var name = document.getElementById('name').value;
var currentAge = document.getElementById('currentAge').value;
var Birthday = document.getElementById('Birthday').value;
var carType = document.getElementById('carType').value;
var table = document.getElementsByTagName('table')[0];
const index = table.rows.length;
var newRow = table.insertRow(index);
newRow.setAttribute('data-index', index);
var cel1 = newRow.insertCell(0);
var cel2 = newRow.insertCell(1);
var cel3 = newRow.insertCell(2);
var cel4 = newRow.insertCell(3);
var cel5 = newRow.insertCell(4);
cel1.textContent = name;
cel2.textContent = currentAge;
cel3.textContent = Birthday;
cel4.textContent = carType;
cel5.innerHTML = '<button onclick="removeRow(this)" type="button" class="delete-button">Delete</button>';
}
function myFunction() {
var x = document.getElementById("table").rows.length;
document.getElementById("demo").innerHTML = "Found " + x + "tr elements in the table.";
}
function removeRow(evt) {
const deleteIndex = evt.parentElement.parentElement.rowIndex;
document.getElementById("table").deleteRow(deleteIndex);
}
table,
th {
border: 1px solid black;
}
tbody td {
padding: 30px;
}
tbody tr:nth-child(odd) {
background-color: #F4BC01;
color: #ABC412;
}
<h2>Basic HTML table</h2> <button onclick="myFunction()">Press me for
elements amount</button>
<p id ="demo"></p>
Name: <input type="text" name="name" id="name" /><br/><br/>
Age: <input type="text" name="currentAge" id="currentAge" /><br/><br/>
Date of Birth <input type="date" name="Birthday" id="Birthday" /><br/>
<button onclick="addRow();">Display</button><br/><br/>
<p>Eye Colour:</p>
<select id="carType">
<option value="ferrari" id="ferrari">Ferrari</option>
<option value="lamborghini" id="lamborghini">Lamborghini</option>
<option value="porsche" id="porsche">Porsche</option>
<option value="bugatti" id="bugatti">Bugatti</option>
<option value="pagani" id="pagani">Pagani</option>
</select>
<table border="1" id="table">
<tr>
<th>Name</th>
<th>Age</th>
<th>Birthday</th>
<th>CarType</th>
<th>Delete</th>
</tr>
</table>
</body>
</html>
What you should be doing is that you set the innerHTML of cel5 to a button, e.g.:
cel5.innerHTML = '<button type="button" class="delete-button">Delete</button>';
Then, you can simply add a click event listener on the table, and check if a click event has emitted from the button element. If it matches, you then delete the closest <tr> element:
document.getElementById('table').addEventListener('click', function(e) {
// Check if click event came from delete button
if (!e.target.classList.contains('delete-button'))
return;
e.target.closest('tr').remove();
});
See proof-of-concept example below:
function addRow() {
// get input values
var name = document.getElementById('name').value;
var currentAge = document.getElementById('currentAge').value;
var Birthday = document.getElementById('Birthday').value;
var carType = document.getElementById('carType').value;
var table = document.getElementsByTagName('table')[0];
var newRow = table.insertRow(table.rows.length / 2 + 1);
var cel1 = newRow.insertCell(0);
var cel2 = newRow.insertCell(1);
var cel3 = newRow.insertCell(2);
var cel4 = newRow.insertCell(3);
var cel5 = newRow.insertCell(4);
cel1.innerHTML = name;
cel2.innerHTML = currentAge;
cel3.innerHTML = Birthday;
cel4.innerHTML = carType;
cel5.innerHTML = '<button type="button" class="delete-button">Delete</button>';
}
function myFunction() {
var x = document.getElementById("table").rows.length;
document.getElementById("demo").innerHTML = "Found " + x + "tr elements in the table.";
}
document.getElementById('table').addEventListener('click', function(e) {
// Check if click event came from delete button
if (!e.target.classList.contains('delete-button'))
return;
e.target.closest('tr').remove();
});
<h2>Basic HTML table</h2> <button onclick="myFunction()">Press me for
elements amount</button>
<p id="demo"></p>
Name: <input type="text" name="name" id="name" /><br/><br/> Age: <input type="text" name="currentAge" id="currentAge" /><br/><br/> Date of Birth <input type="date" name="Birthday" id="Birthday" /><br/>
<button onclick="addRow();">Display</button><br/><br/>
<p>Eye Colour:</p>
<select id="carType">
<option value="ferrari" id="ferrari">Ferrari</option>
<option value="lamborghini" id="lamborghini">Lamborghini</option>
<option value="porsche" id="porsche">Porsche</option>
<option value="bugatti" id="bugatti">Bugatti</option>
<option value="pagani" id="pagani">Pagani</option>
</select>
<table border="1" id="table">
<tr>
<th>Name</th>
<th>Age</th>
<th>Birthday</th>
<th>CarType</th>
<th>Actions</th>
</tr>
</table>
In the head, add a function that understands rows and cells. Call some delete on a parent of a cell (Delete the <tr> in which the <td> is located at). then on the body add to each dynamic button an onClick event and set that function you created earlier ON.
You can use a script like this:
function deleteRow() {
var tableData = event.target.parentNode;
var tableRow = tableData.parentNode;
tableRow.parentNode.removeChild(tableRow);
}
In the button you create (dynamically or fixedly) you should add an onClick event. For example:
<tr>
<td>John Doe</td>
<td>$10,000</td>
<td><input type="submit" value="Delete" id="Delete" onclick="deleteRow()"></td>
</tr>

Loop through dynamically generated HTML elements with the same Class and build objects with their data

I am trying to collect data from a table that is dynamically generated on a button click. As you will see below, the button creates a new text box and a multiselect drop down. Currently, my code will only grab the first value from both the textbox and the dropdown.
My end goal is to create an object of key/values that will look like this:
{"group 1":[multiselect value, multiselect value], "group 2": [multiselect value, multiselect value, multiselect value], "group 3": [multiselect value, multiselect value]}
Below is my current code. Any guidance is appreciated!
function servicePackageAdd()
{
var serviceName = document.getElementById('servicePackageText').value;
var serviceList = document.querySelectorAll('.service');
var serviceGroupName = [];
for (var i = 0; i < serviceList.length; i++)
{
serviceGroupName.push(serviceList[i].querySelector('input.packageGroupName').value);
var sourceType = document.querySelector('select#multiple-checkboxes');
var serviceArray = [];
for (i = 0; i < sourceType.selectedOptions.length; i++)
{
serviceArray.push(parseInt(sourceType.selectedOptions[i].value));
}
var groupName = {};
groupName[serviceGroupName] = serviceArray;
ungroupedServiceArray = [];
}
}
document.getElementById('addGroup').onclick = duplicate;
function duplicate()
{
var original = document.getElementById('addService');
var rows = original.parentNode.rows;
var i = rows.length - 1;
var clone = original.cloneNode(true); // "deep" clone
clone.id = "duplic" + (i); // there can only be one element with an ID
original.parentNode.insertBefore(clone, rows[i]);
}
var divs = ["addService"];
var visibleDivId = null;
function toggleCheckbox(divId)
{
if(visibleDivId === divId)
{
visibleDivId = null;
} else
{
visibleDivId = divId;
}
hideNonVisibleDivs();
}
function hideNonVisibleDivs()
{
var i, divId, div;
for(i = 0; i < divs.length; i++)
{
divId = divs[i];
div = document.getElementById(divId);
if(visibleDivId === divId)
{
div.style.display = "block";
}
else
{
div.style.display = "none";
}
}
}
function servicePackageName()
{
var servicePackageName = document.getElementById('servicePackageText').value;
var servicePackageNameBold = servicePackageName.bold().fontcolor('#337ab7');
document.getElementById('servicePackageInputName').innerHTML = servicePackageNameBold;
}
<div>
<div class="servicePackageCreation">
<h2><b>Service Package Administration</b></h2>
<br>
<span><p><b>Create Service Package: </b></p><p id="servicePackageInputName"></p></span>
<div class="form-group">
<input type="text" class="form-inline" id="servicePackageText" minlength= 1 placeholder=" Service Package Name" required>
<button type="button" class="btn btn-primary" onclick="toggleCheckbox('addService'); servicePackageName();" id="addGroupsAndServices">Next</button>
</div>
<table>
<tr id="addService" class="service" style="display:none">
<td>
<span><b>Service Group Name</b></span>
<input type="text" name="servicetype" id="packageGroupName" class="packageGroupName"/>
</td>
<td>
<span><b>Add Services</b></span>
<select id="multiple-checkboxes" multiple="multiple">
<?php echo $servicehtml ?>
</select>
</td>
</tr>
<tr>
<td>
<button id="addGroup" class="btn btn-primary" onclick="duplicate()">Add More</button>
</td>
</tr>
</table>
<button type="button" class="btn btn-success test1234" onclick="confirmAddButton()" id="adminBulkConfirm">Create</button>
<br>
<br>
</div>
Using Object.values Array#map and Array#reduce.
const services = document.querySelectorAll(".service");
const res = Object.values(services)
.map((service, i) => {
const inputText = service.querySelector('.packageGroupName').value;
return {
[inputText]: [...service.querySelectorAll('option:checked')].map(o => Number(o.value))
}
})
.reduce((a, c) => ({ ...a,...c}), {});
console.log(res);
table {
display: none;
}
<table>
<tr class="service">
<td>
<span><b>Service Group Name</b></span>
<input type="text" name="servicetype" id="packageGroupName" class="packageGroupName" value="Banana" />
</td>
<td>
<span><b>Add Services</b></span>
<select class="multiple-checkboxes" multiple="multiple">
<option value="1" selected>12</option>
</select>
</td>
</tr>
<tr class="service">
<td>
<span><b>Service Group Name</b></span>
<input type="text" name="servicetype" id="packageGroupName" class="packageGroupName" value="Orange" />
</td>
<td>
<span><b>Add Services</b></span>
<select class="multiple-checkboxes" multiple>
<option value="2" selected>2</option>
<option value="3" selected>3</option>
<option value="4">4</option>
</select>
</td>
</tr>
<tr>
<td>
<button class="btn btn-primary" onclick="duplicate()">Add More</button>
</td>
</tr>
</table>

I have created a table with some records using with JavaScript only, I want to set my array with objects to local Storage

var items2 = [
{name:'HP 1Laptop', id:'Item1251', price:1001},
{name:'HP 2Laptop', id:'Item1252', price:1002},
{name:'HP 3Laptop', id:'Item1253', price:1003},
{name:'HP 4Laptop', id:'Item1254', price:1004},
{name:'HP 5Laptop', id:'Item1250', price:1005},
{name:'HP 6Laptop', id:'Item1256', price:1006},
{name:'HP 7Laptop', id:'Item1257', price:1007},
{name:'HP 8Laptop', id:'Item1258', price:1008},
];
var items = [];
function saveData(){
localStorage.setItem('localData', JSON.stringify(items2))
}
function loadData(){
var arr1 = localStorage.getItem('localData');
items = JSON.parse(arr1);
}
saveData();
loadData();
var globalIndex;
var updateBtn = document.getElementById('updateRow');
var addBtn = document.getElementById('addBtn');
var numberFieldValue = document.getElementById('numberOfRecords');
var recordsCounting = document.getElementById('counter');
var updatedRow = document.getElementById('countries');
function recordsLoading(){
var data='';
if(items.length >= 0){
for(var i = 0; i< items.length; i++){
data+= '<tr>';
data+= '<td>'+ items[i].name +'</td>';
data+= '<td>'+ items[i].id +'</td>';
data+= '<td>'+ items[i].price +'</td>';
data+= '<td><button class="btn btn-info" onclick="editingRecord('+i+')">Edit</button> <button class="btn btn-danger" onclick="delRecord('+i+')">Delete</button></td></tr>';
}
document.getElementById('countries').innerHTML = data;
}
recordsCounting.innerText = items.length ;
}
recordsLoading();
/*From Here CRUD Operations are started*/
/*get the userdata from the current input fields*/
var itemName = document.getElementById('addNewitemName');
var itemId = document.getElementById('addNewitemID');
var itemprice = document.getElementById('addNewitemPrice');
/*This is for Adding records to the table*/
function addingRecord(){
if(itemName.value!=='' && itemId.value!=='' && itemprice.value !== ''){
items.push({name:itemName.value, id:itemId.value,price:itemprice.value});
items2.push({name:itemName.value, id:itemId.value,price:itemprice.value});
recordsLoading();
itemName.value = '';
itemId.value = '';
itemprice.value = '';
}
itemName.focus();
}
/*This is For Deleting a record from the table*/
function delRecord(indexValue){
items.splice(indexValue, 1);
recordsLoading();
}
/*This is for to edit existing record values*/
function editingRecord(indexValue){
itemName.value = items[indexValue].name;
itemId.value = items[indexValue].id;
itemprice.value = items[indexValue].price;
updateBtn.style.display = 'inline-block';
addBtn.style.display = 'none'
globalIndex = indexValue;
}
/*This is for update edited Value in the Table*/
function update(){
items[globalIndex].name = itemName.value;
items[globalIndex].id = itemId.value;
items[globalIndex].price = itemprice.value;
itemName.value = "";
itemId.value = "";
itemprice.value= "";
recordsLoading();
}
<!-- I need to retrieve my data from local Storage, I know local
storage concept but I don't know how it works with real time
data -->
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Countries CRUD</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<style>
#updateRow{
display: none;
}
.scrollView{
max-height:350px;
overflow-Y:auto;
}
</style>
</head>
<body>
<div class="container">
<hr/>
<form action="#">
<div class="form-group">
<table class="table table-bordered table-striped">
<!-- <tr> -->
<!-- <td colspan="3"><input type="number" id="numberOfRecords" placeholder="Enter Number Of Items To Disaplay in Below Table" class="form-control"></td> -->
<!-- <td><button class="btn btn-info btn-block" onclick="renderRecords();">Create</button></td> -->
<!-- </tr> -->
<tr>
<td><input type="text" id="addNewitemName" placeholder="Enter Item Name" class="form-control"></td>
<td><input type="text" id="addNewitemID" placeholder="Enter Item ID" class="form-control"></td>
<td><input type="number" id="addNewitemPrice" placeholder="Enter Item Price" class="form-control"></td>
<td width="150"><button onclick="addingRecord()" id="addBtn" class="btn btn-primary btn-block">Add</button><button class="btn btn-info" id="updateRow" onclick="update()"> Update </button></td>
</tr>
</table>
</div>
</form>
<div style="padding:5px 0px;">
<button type="button" class="btn btn-success">
Available Records : <span class="badge badge-light" id="counter"></span>
</button>
</div>
<div class="scrollView">
<table class="table table-bordered">
<tr>
<th onclick="sorting('name');">Name</th>
<th onclick="sorting('id')">Item ID</th>
<th onclick="sorting('price')" >Item Price</th>
<th width="150"></th>
</tr>
<tbody id="countries">
</tbody>
</table>
</div>
<button class="btn btn-warning" onclick="saveData();">Save Data</button>
<button class="btn btn-warning" onclick="loadData();">Retrive Data</button>
</div>
</body>
</html>
To save an array of objects into localStorage first stringify that array of objects, then save it into localStorage. When it is retrieved from localStorage parse it to get the initial array.
To save anything into the localStorage use localStorage.setItem('name',value);
By default the item saved in localStorage becomes String type.
To retrieve the saved item from localStorage, use localStorage.getItem('name');
var items = [
{name:'HP 1Laptop', id:'Item1251', price:1001},
{name:'HP 2Laptop', id:'Item1252', price:1002},
{name:'HP 3Laptop', id:'Item1253', price:1003},
{name:'HP 4Laptop', id:'Item1254', price:1004},
{name:'HP 5Laptop', id:'Item1250', price:1005},
{name:'HP 6Laptop', id:'Item1256', price:1006},
{name:'HP 7Laptop', id:'Item1257', price:1007},
{name:'HP 8Laptop', id:'Item1258', price:1008},
];
localStorage.setItem('array' , JSON.stringify(items));
console.log("saved array is\n", JSON.parse(localStorage.getItem('array')));
You can find the complete details of the localStorage from here:
https://developer.tizen.org/community/tip-tech/html5-local-storage
which helps you achieve your goal.
In short overview, just use the following code to set the array:
localStorage.setItem("list_data_key", JSON.stringify(ArrayData));
To retrieve it, use this:
var storedData = localStorage.getItem("list_data_key");
if (storedData) {
ArrayData = JSON.parse(storedData);
}

Categories

Resources