Make a table row editable on click with Javascript - 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();
}

Related

How I get values updating/refreshing related input areas in Javascript?

I have a form and when I press the Try button it returns values for the 3rd and 6th input fields of the form according to the values entered in 1,2 and 5.6. Also, the 7th input field combines the 3rd and 6th results.
My question is how can I get the result values from input fields 3 and 6 without clicking the Try It button and also update the input field 7 without refreshing the page?
My code is in JSFiddle UPDATED !!
My Javascript are:
<script type="text/javascript">
function concatenate(/*String*/string_one, /*String*/string_two, /*boolean*/with_space) {
if (with_space===true) {
return string_one+'/'+string_two;
}
else {
return string_one+string_two;
}
}
function join_names() {
var input_name_first = document.getElementsByName('ht')[0].value;
var input_name_last = document.getElementsByName('ft')[0].value;
var input_name_full = document.getElementsByName('htft')[0];
var var_name_full = concatenate(input_name_first, input_name_last, true);
input_name_full.value = var_name_full;
}
</script>
<script type="text/javascript">
function myFunctionFt() {
var home = document.getElementById("home_score").value;
var away = document.getElementById("away_score").value;
var results;
if (home > away) {
results = "1";
} else if (home < away) {
results = "2";
} else if (home = away) {
results = "X";
}
document.getElementById("ft").value = results;
}
</script>
<script type="text/javascript">
function myFunctionHt() {
var home = document.getElementById("home_ht_score").value;
var away = document.getElementById("away_ht_score").value;
var results;
if (home > away) {
results = "1";
} else if (home < away) {
results = "2";
} else if (home = away) {
results = "X";
}
document.getElementById("ht").value = results;
}
</script>
I have removed all the previous answers from this answer and added a new answer in place. I have read your last comment and you said that my code was not working for the Home Team HT Score and Away Team HT Score. Well, I had made the logic to behave this way because it makes more sense to put the result in HT Result once both of the teams have played or in other words when we have both of the inputs. In sports, it rarely happens that only one team plays. Right. So outputting the result in HT result based on one of the inputs makes no sense. But if this is what you want, you simply have to change the logic from if (!input_home || !input_away) return; to if (!input_home && !input_away) return; and it will start working the way you want. Basically in the first logic statement with "||" we are saying unless both of the inputs are available don't out into HT result and in the second statement with && we are saying id doesn't matter if one of them is not present, just take whatever is present and output it in HT result. The same thing is happening for FT. You just have to change || to &&.
Here is the final working code:
//FT and HT Result//
let name_first = document.getElementById('ht');
let name_last = document.getElementById('ft');
let input_name_first = name_first.value;
let input_name_last = name_last.value;
//HT Home//
let home = document.getElementById("home_ht_score");
let away = document.getElementById("away_ht_score");
home_ht_score.addEventListener("input", myFunctionHt);
away_ht_score.addEventListener("input", myFunctionHt);
let input_away = away.value;
let input_home = home.value;
//FT Home//
let home_ft = document.getElementById("home_score");
let away_ft = document.getElementById("away_score");
home_score.addEventListener("input", myFunctionFt);
away_score.addEventListener("input", myFunctionFt);
let input_ft_away = away_ft.value;
let input_ft_home = home_ft.value;
function myFunctionHt() {
input_away = away.value;
input_home = home.value;
input_name_first = name_first.value;
input_name_last = name_last.value;
if (!input_home && !input_away) return;
var results = "";
if (input_home > input_away) {
results = "1";
} else if (input_home < input_away) {
results = "2";
} else if (input_home = input_away) {
results = "X";
}
document.getElementById("ht").value = results;
join_names();
}
function myFunctionFt() {
input_ft_away = away_ft.value;
input_ft_home = home_ft.value;
input_name_first = name_first.value;
input_name_last = name_last.value;
if (!input_ft_home && !input_ft_away) return;
var results = "";
if (input_ft_home > input_ft_away) {
results = "1";
} else if (input_ft_home < input_ft_away) {
results = "2";
} else if (input_ft_home = input_ft_away) {
results = "X";
}
document.getElementById("ft").value = results;
join_names();
}
function join_names() {
if (!input_name_first && !input_name_last) return;
let input_name_full = document.getElementsByName('htft')[0];
var var_name_full = concatenate(name_first.value, name_last.value, true);
input_name_full.value = var_name_full;
}
function concatenate(/*String*/string_one, /*String*/string_two, /*boolean*/with_space) {
if (with_space===true) {
return string_one+'/'+string_two;
}
else {
return string_one+string_two;
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<form class="form-group" action="addemp" method="post" onsubmit="return true" onClick="return false">
<table border="0" cellpadding="1">
<tbody>
<tr>
<td> <label class="form-label" style="color:blue" for="name">Home Team HT Score</label> </td>
<td> <input id="home_ht_score" name="home_ht_score" type="text" class="form-control mb-3" style="width: 200px;"></td>
</tr>
<tr>
<td> <label class="form-label" style="color:red" for="name">Away Team HT Score</label> </td>
<td> <input id="away_ht_score" name="away_ht_score" type="text" class="form-control mb-3" style="width: 200px;"></td>
</tr>
<tr>
<td><label class="form-label" style="color:green" for="name">HT Result</label> </td>
<td> <input id="ht" name="ht" type="text" class="form-control mb-3" oninput="join_names();" onpaste="join_names();" style="width: 200px;"></td>
</tr>
<tr>
<td><label class="form-label" style="color:blue" for="name">Home FT Score</label> </td>
<td> <input id="home_score" name="home_score" type="number" class="form-control mb-3" style="width: 200px;"></td>
</tr>
<tr>
<td><label class="form-label" style="color:red" for="name">Away FT Score</label> </td>
<td> <input id="away_score" name="away_score" type="number" class="form-control mb-3" style="width: 200px;"></td>
</tr>
<tr>
<td> <label class="form-label" style="color:green" for="name">FT Result</label> </td>
<td> <input id="ft" name="ft" type="text" class="form-control mb-3" onchange="join_names();" onpaste="join_names();" style="width: 200px;"></td>
</tr>
<tr>
<td><label class="form-label" style="color:green" for="name">HT/FT</label> </td>
<td> <input name="htft" type="text" class="form-control mb-3" style="width: 200px;"> </td>
</tr>
<tr>
<td> </td>
<td><button class="btn btn-primary mb-4" type="submit">Save Match Result</button> </td>
</tr>
</tbody>
</table>
</form>
</body>
</html>

button functionality for selected items JS

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>

Access to input values created by javascript function

I have a form within a table with Title and description columns and the rows can be added dynamically by a button. I need to access and save the input values in text boxes created by javascript function when saving the form by save button. the input values are later saved on local storage. The saved values are used to repopulate the form in case of unsuccessful validation.
function add_text_input() {
var table = document.getElementById('mytable');
var x = table.rows.length;
table.insertRow(-1).innerHTML = '<tr>' +
'<td> <input type="text" id="title' + x + '" /></td>' +
'<td> <input type="text" id="description' + x + '" /></td></tr>';
}
function save_data() {
var table = document.getElementById('mytable');
var tableRows = table.rows.length;
var data = [];
for (var i = 1; i <= tableRows; i++) {
for (var j = 0; j < 2; j++) {
var title = document.getElementById('title' + i).value;
var desc = document.getElementById('description' + i).value;
var temp = {
title: title,
description: desc
};
data.push(temp);
}
}
window.localStorage.setItem('Table1', JSON.stringify(data));
}
<form>
<table id="mytable">
<tr>
<td> Title </td>
<td> Description </td>
</tr>
</table>
<input type="button" onclick="add_text_input()" value="add row">
<input type="button" onclick="save_data()" value="save">
</form>
did you mean something like this?
$(document).ready(()=>{
$('#container').append('<input id="addedTxt" type="text" />');
$('#addedTxt').val('Test');
$('#saveBtn').on('click', ()=>{
alert($('#addedTxt').val());
});
});
<div id="container">
</div>
<input id="saveBtn" type="button" value="save" />
(using jquery)
https://jsfiddle.net/u6vnxwzc/1/#&togetherjs=rQ2b5IsJQ1
or where is the problem?
In your code why you use the second For loop? I think it is not necessary.
find the working code snippet
https://s.codepen.io/mastersmind/debug/VNyKrY/DqADdKoRXEjA
function add_text_input() {
var table = document.getElementById('mytable');
var x = table.rows.length;
table.insertRow(-1).innerHTML = '<tr>' +
'<td> <input type="text" id="title'+x+'" /></td>'+
'<td> <input type="text" id="description'+x+'" /></td></tr>';
}
function save_data(){
var table = document.getElementById('mytable');
var tableRows = table.rows.length;
var data = [];
for (var i = 1; i <= tableRows-1; i++) {
var title = document.getElementById('title'+ i).value;
var desc = document.getElementById('description'+ i).value;
var temp = {title: title, description: desc};
data.push(temp);
}
window.localStorage.setItem('Table1', JSON.stringify(data));
}
loadData = function(){
let data = JSON.parse(window.localStorage.getItem('Table1'));
for(i=0; i<data.length;i++){
add_text_input();
document.getElementById('title'+ (i+1)).value = data[i].title;
document.getElementById('description'+ (i+1)).value = data[i].description;
}
}
loadData();
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form>
<table id="mytable">
<tr>
<td> Title </td>
<td> Description </td>
</tr>
</table>
<input type="button" onclick="add_text_input()" value="add row">
<input type="button" onclick="save_data()" value="save">
</form>
</body>
</html>

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>

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