sending attachment in javascript object server-side Google Code.gs - javascript

Anyone know how I can send an array of objects that includes an attachment?
I'm working on a WebApp that captures weekly mileage entries. At the end of the week, a user can submit their miles driven and attach a parking receipt.
I was able to send the array of object to the server-side Code.gs UNTIL I tried to include a file input for each day.
document.addEventListener("DOMContentLoaded", function() {
document.getElementById("tripPost").addEventListener("click", addLine);
document.getElementById("submitAll").addEventListener("click", addRecord);
});
//global variables for next functions
var submit = document.getElementById("tripPost");
var submittedTable = document.getElementById("submitted-data");
var mainEntry = document.getElementById("entry-table");
var submitAll = document.getElementById("submitAll");
submittedTable.addEventListener("click", addLine);
submittedTable.addEventListener("change", fileUpload);
function addLine() {
document.getElementById("table-container").style.display = "block";
var date = document.getElementById("date1").value;
var efirst = document.getElementById("efirst").value;
var elast = document.getElementById("elast").value;
var row = document.createElement("tr");
var col1 = document.createElement("td");
col1.appendChild(document.createTextNode(date));
col1.className = "postDateClass";
var col2 = document.createElement("td");
col2.appendChild(document.createTextNode(efirst));
col2.className = "postEfirstClass";
var col3 = document.createElement("td");
col3.appendChild(document.createTextNode(elast));
col3.className = "postElastClass";
var col4 = document.createElement("td");
row.appendChild(col1);
row.appendChild(col2);
row.appendChild(col3);
row.appendChild(col4);
submittedTable.appendChild(row);
var uniqueID = "id" + new Date().getTime();
var upload = document.createElement("input");
upload.type = "file";
upload.id = uniqueID;
upload.name = "myReceipt";
upload.className = "uploadClass";
var label = document.createElement("label");
label.innerHTML = "upload me please!";
label.htmlFor = uniqueID;
label.className = "custom-file-upload";
var form = document.createElement("form");
form.appendChild(upload);
form.appendChild(label);
col4.appendChild(form);
}
function fileUpload(e) {
if (e.target.className === "uploadClass") {
if (e.target.value) {
var span = document.createElement("span");
span.className = "uploadSpanText";
span.innerHTML = e.target.value.match(/[\/\\]([\w\d\s\.\-\(\)]+)$/)[1];
e.target.parentElement.appendChild(span);
e.target.nextElementSibling.innerHTML = "uploaded!";
e.target.nextElementSibling.style.border = "1px solid #a8e0b4";
e.target.nextElementSibling.style.color = "#8bca9e";
}
}
}
function getFile(file) {
return new Promise(resolve => {
const fr = new FileReader();
fr.onload = e => {
const data = e.target.result.split(",");
const obj = {
fileName: file.name,
mimeType: data[0].match(/:(\w.+);/)[1],
data: data[1]
};
resolve(obj);
};
if (file) {
fr.readAsDataURL(file);
} else {
reject("No File");
}
});
}
//gathers inputs and stores values in an object and runs the "addLine" function
async function addRecord(e) {
var dateLines = document.querySelectorAll(".postDateClass");
var eFirstLines = document.querySelectorAll(".postEfirstClass");
var eLastLines = document.querySelectorAll(".postElastClass");
var attachmentLines = document.querySelectorAll(".uploadClass");
var mileageData = [];
for (var i = 0; i < dateLines.length; i++) {
var mileageLines = {};
mileageLines.travelDate = dateLines[i].textContent;
mileageLines.firstName = eFirstLines[i].textContent;
mileageLines.lastName = eLastLines[i].textContent;
mileageLines.receipt = await getFile(attachmentLines[i].parentNode);
mileageData.push(mileageLines);
}
//send object to google. resets input elements
google.script.run.userMileageSubmit(mileageData);
}
Here is the HTML for the code that I'm working with.
<div id="entry-table">
<table>
<h3 style="text-align:left"><u><b>Enter mileage information below.</b></u><br></h3>
<thead>
<tr>
<th >Date</th>
<th >First:</th>
<th >Last:</th>
</tr>
</thead>
<tbody id="table-data">
<tr>
<td>
<div class="disabled-results" id="date">
<input placeholder="Start Date" id="date1" type="text" class="datekeeper" required>
<label for="date1" class="active">Date:</label>
</div>
<td>
<div class="disabled-results">
<input id ="efirst" type="text" class="validate" >
<label for="efirst" class="active">First:</label>
</div>
</td>
<td>
<div class="disabled-results">
<input id ="elast" type="text" class="validate" >
<label for="elast" class="active">Last:</label>
</div>
</td>
<td>
<div id="status">
<button id="tripPost" class="waves-effect waves-light btn-small blue darken-3">Add Trip</button>
</div>
</td>
</tr>
</tbody>
</table>
</div><!---CLOSE ROW --->
<div class="autocomplete" id="table-container" style=display:none>
<table>
<thead>
<tr id="header-titles">
<th >Date</th>
<th >First:</th>
<th >Last:</th>
<th >Receipt </th>
</tr>
</thead>
<form>
<tbody class="form" id="submitted-data">
<div>
<p>Thank you!</p>
</div>
</form>
</tbody>
</table>
<br><br>
</div>
<center>
<div class="row">
<button id="submitAll" class="waves-effect waves-light btn btn-large blue darken-3"><i class="material-icons left">directions_car</i>Submit All Mileage!</button>
</div>
</center>
Here is the CSS
body {
background-color: lightblue;
margin-top: 80px;
margin-bottom: 80px;
margin-right: 80px;
margin-left: 80px;
}
h1{
color: black;
text-align: center;
}
div.disabled-results{
width: 175px;
height: 80px;
padding: 5px;
margin: 5px;
display: inline-table;
box-sizing: border-box;
text-align: center;
}
input[type="file"]{
display: none;
}
.custom-file-upload{
border: 2px solid #000;
width: 85px;
display: inline-block;
padding: 2px 1px;
cursor: pointer;
text-align: center;
}
div.autocomplete{
width: 55px;
height: 80px;
padding: 5px;
margin: 5px;
display: inline-table;
box-sizing: border-box;
text-align: center;
}
I got everything else to work, except sending the attachment (if any) in each line as part of the object.
I am sure that it can be done. I tried to implement the solution from this video which shows you how to upload a file, but I don't use the onclick or this.parentNode since I'm not uploading immediately after selecting a file and instead doing a bulk upload when a user has made numerous entries.
Any help in understanding how this should work would be greatly appreciated.
Thank you.

Please see https://developers.google.com/apps-script/guides/html/communication#forms. You'll want to send the form element to the server side script.

Given that you push several mileageLines into the array mileageData, your data will look like this:
[{...,claimMiles=claimMilesLines[0].textContent; receipt=attachmentLines[0].files[0]}, {...,claimMiles=claimMilesLines[1].textContent;, receipt=attachmentLines[1].files[0]},...]
This means that you need to access your data as array elements
var file1 = responses[0].receipt;
var file2 = responses[1].receipt;
Or
for( var i = 0; i < responses.length; i++){
var file = responses[i].receipt;
...
var createFile = mainFolder.createFile("formfile", file);
}

Related

Read values from text field individually

I would like to read all values from a text field/text box individually and then write them to a table:
Example:
This is an example of a text I want to read out.
Output:
This
is
an
example
of
a
text
I
want
to
read
out
How can I use a loop to read the text field/textbox?
That is, whenever a space comes the new subsequent value must be in a new line.
String:
var table = document.getElementById("table");
var phrase = "This is an example of a text I want to read out";
var words = phrase.split(" ");
for (var i = 0; i < words.length; i++) {
var tableCol =
`<tr>
<td>${i+1}:</td>
<td>${words[i].replace(/[\.,!\?]/g," ")}<td>
</tr>`;
document.querySelector('table tbody').innerHTML += tableCol;
}
#table {
border: 1px solid;
}
th {
border: 1px solid;
padding: 5px;
}
<table id="table">
<thead>
<th>Number:</th>
<th>Word:</th>
<thead>
<tbody>
</tbody>
</table>
Input:
var table = document.getElementById("table");
var myBtn = document.getElementById("myBtn");
var myInput = document.getElementById("myInput");
myBtn.addEventListener('click', () => {
document.querySelector('tbody').innerHTML = '';
var phrase = myInput.value;
var words = phrase.split(" ");
for (var i = 0; i < words.length; i++) {
var tableCol =
`<tr>
<td>${i+1}:</td>
<td>${words[i].replace(/[\.,!\?]/g," ")}<td>
</tr>`;
document.querySelector('tbody').innerHTML += tableCol;
}
});
input {
margin-bottom: 10px;
width: 300px;
height: 25px;
}
#table {
border: 1px solid;
}
th {
border: 1px solid;
padding: 5px;
}
<input id="myInput" type="text">
<button id="myBtn">Create Table</button>
<table id="table">
<thead>
<th>Number:</th>
<th>Word:</th>
<thead>
<tbody>
</tbody>
</table>
Shorter and removing punctuation
const str = `This is an example of a text I want to read out.`;
document.querySelector('table tbody').innerHTML = str.split(" ")
.map((word,i) => `<tr><td>${i+1}:</td><td>${word.replace(/[\.,!\?]/g,"")}<td></tr>`)
.join("");
<table id="table">
<thead>
<th>Number:</th>
<th>Word:</th>
<thead>
<tbody>
</tbody>
</table>

Store form data in Local Storage and display in table

How to store form input data? How to get it back and take actions like update, delete and clear?
Storing data using localStorage.setItem();
Getting data using localStorage.getItem();
I am taking user input and trying to save locally using JSON. Want to get data using JSON parse save it in table form. Want to take some actions like ADD Data, DELETE data on click. Clear the table using clear data () function. So I have related functions.
I am new. Didn't understand the logic completely.
HTML FORM:
<form id="form">
<label for="fname">First name:
<input type="text" id="fname" name="fname" placeholder
="name">
</label><br>
<label for="lname">Last name:
<input type="text" id="lname" name="lname"><br>
</label><br>
<button class="btn">Add</button>
<button class="btn">Clear List</button>
</form>
<table id="myTable">
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th> Action</th>
</tr>
<tableBody id="tabledata">
<tr>
<td>cc </td>
<td> qq </td>
<td><button class="btn">Delete</button></td>
</tr>
</tableBody>
</table>
SCRIPT:
let myfName = document.getElementById("fName").value;
let mylName = document.getElementById("lName").value;
if(localStorage.getItem('itemJson') == null){
itemJsonArray =[];
itemJsonArray
.push([ myfName, mylName]);
localStorage.setItem('itemJeson',
JSON.stringify(itemJsonArray))
}
else{
itemJsonArrayStr
localStorage.getItem('itemJeson');
itemJsonArry = JSON.parse(
itemJsonArrayStr);
itemJsonArray
.push([ myfName, mylName]);
localStorage.setItem('itemJeson',
JSON.stringify(itemJsonArray))
}
update();
// updating inputs in table
function update(){
if(localStorage.getItem('itemJson') == null){
itemJsonArray =[];
localStorage.setItem('itemJeson',
JSON.stringify(itemJsonArray))
}
else{
itemJsonArrayStr =
localStorage.getItem('itemJeson');
itemJsonArry = JSON.parse(
itemJsonArrayStr);
}
let tableData document.getElementById("tabledata");
let str = "";
itemJsonArray.forEach((element, index) => {
str += ` <tr>
<th scope="row"> ${index}</th>
<td> ${element[0]}</td>
<td> ${element [1]}</td>
<td><button class="btn btn-warning btn-sm" onclick = "deleted(${index}" >Delete</button></td>
</tr>`;
});
tablebody.innerHTML = str;
}
let add = document.getElementById("addItem");
add.addEventListener("click", getAndUpdate);
update();
<!DOCTYPE html>
<html>
<body>
<style>
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
}
td, th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
</style>
<div id="result"></div>
<input id="data"></input>
<input type="date" id="date" name="date" value="2018-07-22" min="2018-01-01" max="2018-12-31">
<button onclick="Submit()">Submit</button>
<button onclick="Clear()">Clear</button>
<br><br><br><br><br>
<table id="table">
<tr>
<th>SL. NO</th>
<th>Task Name</th>
<th>Date</th>
</tr>
<tr id ="tbl_data">
</tr>
<tr>
</table>
<script>
// Check browser support
var taskData = [];
var i = null;
function Submit(){
if(taskData.length > 0){
var data = document.getElementById('data').value;
var date = document.getElementById('date').value;
const obj = { "data": data , "date": date}
var stored = JSON.parse(localStorage.getItem("task"));
stored.push(obj);
}
var data = document.getElementById('data').value;
var date = document.getElementById('date').value;
const obj = { "data": data , "date": date}
taskData.push(obj);
localStorage.setItem("task", JSON.stringify(taskData));
document.getElementById("result").innerHTML = localStorage.getItem("task");
if(i==null){
i= 0;
}
for ( i = i; i < taskData.length; ++i) {
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
row.insertCell(0).innerHTML= i+1;
row.insertCell(1).innerHTML= taskData[i].data;
row.insertCell(2).innerHTML= taskData[i].date;
i=i;
}
}
// Retrieve
</script>
</body>
</html>

How to correctly select a div inside a table cell

I have created a function that inserts table row and data by user's request. I was asked to add a small red square (div) in the right corner of table cell, which when clicked, deletes the table row.
I've got so far that I've written a function that removes the table row, but the problem is - it only needs to be done, when the small red div is clicked, not when the table cell is clicked. How could this be achieved? I've tried several ways how to address the div, but none have worked so far.
Would be really grateful for your assistance.
<button class="btn" onclick="createNewTableElement()">Add</button>
<input id="new-item" type="text" value="item">
<table id="main-table" onclick="deleteRow(obj)">
function createNewTableElement() {
var inputField = document.getElementById("new-item");
if (inputField.value == "") {
return;
}
var row = document.createElement("tr");
var cell = document.createElement("td");
var div = document.createElement("div");
var cellText = document.createTextNode(inputField.value);
cell.appendChild(div);
cell.appendChild(cellText);
row.appendChild(cell);
obj = document.getElementById("main-table");
obj.appendChild(row);
}
function deleteRow(e) {
document.getElementById('main-table').deleteRow(e);
}
I made some changes in your code. Removed deleteRow binded on table and add event only on div element, then find parent row element and removed it from table
Does this help you?
function createNewTableElement() {
var inputField = document.getElementById("new-item");
if (inputField.value == "") {
return;
}
var row = document.createElement("tr");
var cell = document.createElement("td");
var div = document.createElement("div");
div.onclick = deleteRow;
var cellText = document.createTextNode(inputField.value);
cell.appendChild(div);
cell.appendChild(cellText);
row.appendChild(cell);
obj = document.getElementById("main-table");
obj.appendChild(row);
}
function deleteRow(e) {
document.getElementById('main-table').removeChild(e.target.parentElement.parentElement);
}
#main-table div {
height: 10px;
width: 10px;
border: 1px solid;
display: inline-block;
margin-right: 10px;
}
<button class="btn" onclick="createNewTableElement()">Add</button>
<input id="new-item" type="text" value="item">
<table id="main-table">
Remove onclick from table:
<button class="btn" onclick="createNewTableElement()">Add</button>
<input id="new-item" type="text" value="item">
<table id="main-table">
Then in same function you are creating row create also red div and event:
function createNewTableElement() {
var inputField = document.getElementById("new-item");
if (inputField.value == "") {
return;
}
var row = document.createElement("tr");
var cell = document.createElement("td");
var div = document.createElement("div");
div.addEventListener('click', function(event) {
// the row call parent (table) and tell removes him self
row.parentNode.removeChild(row);
});
var cellText = document.createTextNode(inputField.value);
cell.appendChild(div);
cell.appendChild(cellText);
row.appendChild(cell);
obj = document.getElementById("main-table");
obj.appendChild(row);
}
my way..
const mainTable = document.querySelector('#main-table tbody')
, btAdd = document.getElementById('btn-Add')
, newItem = document.getElementById('new-item')
;
newItem.oninput=()=>
{
btAdd.disabled = (newItem.value === '')
}
btAdd.onclick=()=>
{
let newCell = mainTable.insertRow().insertCell()
;
newCell.textContent = newItem.value
newCell.appendChild( document.createElement('div'))
newItem.value = ''
btAdd.disabled = true
}
mainTable.onclick=e=>
{
if (!e.target.matches('td div')) return
mainTable.deleteRow( e.target.closest('tr').rowIndex -1 )
}
#main-table {
border-collapse: collapse;
margin: 1em;
}
#main-table thead {
background-color: cadetblue;
}
#main-table th {
padding: .7em;
width:20em;
}
#main-table td {
border: 1px solid grey;
padding: .5em;
}
#main-table td div {
display: block;
float: right;
width: 1em;
height: 1em;
background-color: crimson;
cursor: pointer;
}
#main-table td div:hover {
border: 1px solid blue;
}
<button id="btn-Add" disabled >Add</button>
<input id="new-item" type="text" placeholder="item">
<table id="main-table">
<thead> <th>items list</th> </thead>
<tbody> </tbody>
</table>

Table Cell (td) child?

I am trying to search a table cell that has a child (textarea) in it. I have tried
td.children.value,
td.childNodes.value,
td.firstChild.value,
td.lastChild.value,
td.textarea.value... none of these have worked. here is my snippet:
addCell = function() {
var table = document.getElementById('myTable');
var tr = document.createElement('tr');
var td = document.createElement('td');
var txt = document.createElement('textarea');
table.appendChild(tr);
tr.appendChild(td);
td.appendChild(txt);
}
searchT = function() {
var table = document.getElementById('myTable');
var search = document.getElementById('search');
var tr = document.getElementsByTagName('tr');
var td = document.getElementsByTagName('td');
if (search.value === td.textarea.value) {
alert('hello');
}
/* I have tried:
td.childNodes.value
td.children.value
td.firstChild.value
td.lastChild.value
td.textarea.value
*/
}
td {
background-color: #ccc;
width: 100px;
height: 20px;
}
textarea {
resize: none;
}
.search {
width: 100px;
}
<button onclick="addCell()">
add
</button>
<input id="search" placeholder="search">
<button onclick="searchT()">
search
</button>
<table id="myTable">
<tr>
<td>
<textarea></textarea>
</td>
</tr>
</table>
When you do document.getElementsByTagName(), this returns a list of all the items on the document which contain that tag name. In order to find out if it exists in that list (I'm assuming that's what you want) then you have to loop for the list returned by getElementsByTagName().
I'm also assuming that you want to add a table with whatever you entered in the <input> so I added that in the addCell().
addCell = function() {
var table = document.getElementById('myTable');
var tr = document.createElement('tr');
var td = document.createElement('td');
var txt = document.createElement('textarea');
var search = document.getElementById('search'); // Get value in input field
table.appendChild(tr);
tr.appendChild(td);
txt.innerHTML = search.value; // Set value to table
td.appendChild(txt);
}
searchT = function() {
var search = document.getElementById('search');
var textareas = document.getElementsByTagName('textarea'); // Get the textareas instead
for(var i = 0; i < textareas.length; i++) {
if(search.value === textareas[i].innerHTML) { // If the text matches the search field
console.log("Found: " + search.value + " at index: " + i);
}
}
}
td {
background-color: #ccc;
width: 100px;
height: 20px;
}
textarea {
resize: none;
}
.search {
width: 100px;
}
<button onclick="addCell()">
add
</button>
<input id="search" placeholder="search">
<button onclick="searchT()">
search
</button>
<table id="myTable">
<tr>
<td>
<textarea readonly="readonly">Template</textarea> <!-- This doesn't have to be readonly but I made it Note: readonly="readonly" is only for valid XHTML. It could be left as readonly without the assignment for valid HTML -->
</td>
</tr>
</table>
If you're curious, you can read more about getElementsByTagName() here.
I might start with something like this. The comments should explain what's going on.
// as both functions are using them,
// I can define these outside the functions.
var myTable = document.getElementById("myTable");
var search = document.getElementById('search');
addCell = function() {
// create the references to the new els.
var tr = document.createElement('tr');
var td = document.createElement('td');
var txt = document.createElement('textarea');
// append the new els to my table.
myTable.appendChild(tr);
tr.appendChild(td);
td.appendChild(txt);
}
searchT = function() {
// Get all the td els in my table.
let tdEls = myTable.getElementsByTagName("td");
// Iterate over the array of td els, and
for (let i = 0; i < tdEls.length; i++) {
// get the textarea node if they have one
let textareaEl = tdEls[i].getElementsByTagName("textarea")[0];
// compare the textarea to the search
if (textareaEl.value.includes(search.value)) {
// They match -- do something with them.
console.log(textareaEl.value);
}
}
}
td {
background-color: #ccc;
width: 100px;
height: 20px;
}
textarea {
resize: none;
}
.search {
width: 100px;
}
<button onclick="addCell()">
add
</button>
<input id="search" placeholder="search">
<button onclick="searchT()">
search
</button>
<table id="myTable">
<tr>
<td>
<textarea></textarea>
</td>
</tr>
</table>

JS Array Splice to remove an element in an Array

I have a table being populated by an array containing a list of products and their quantities for an order to be placed by a customer. On the Order confirmation screen the user can remove items in the order by clicking the delete button associated with the particular row.
This is my HTML
<div id="summary">
<table id="ordertable">
<tr><th>Product</th>
<th>Quantity</th>
<th></th>
</tr>
</table>
</div>
This is my JS
if($.cookie('order_cookie') != undefined){
productArray = JSON.parse($.cookie('order_cookie'));
$.cookie('order_cookie', JSON.stringify(productArray), { expires: 1, path: '/' });
}
var ordertable = document.getElementById("ordertable");
//Loop through the array
for(i = 0; i < productArray.length; i ++){
item = productArray[i];
var x = item.split(':');
var row = ordertable.insertRow(1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
cell1.innerHTML = x[0];
cell2.innerHTML = x[1];
cell3.innerHTML = "<input type='button' value='Delete' class='deleteBtn'/>"
}
//Edit Function
$(".editBtn").click(function(){
console.log("Edit clicked");
});
//Delete Function
$(".deleteBtn").click(function(){
console.log(productArray);
var row = this.parentNode.parentNode;
ordertable.deleteRow(row.rowIndex);//remove from the table
productArray.splice(row.rowIndex);//remove from the order array
console.log(productArray);
});
//Confirm order Function
$(".confirmBtn").click(function(){
console.log("Confirm clicked");
});
Currently I can successfully remove elements from the table. However when I try to remove the element from the array it removes the first element of the array
For example:
Array before delete
["EXCEL 5LB BLACK:2", "EXCEL 5LB BLACK:3", "SATO WHITE LABEL:2", "SATO INK PADS:1", "SATO GUN:2"]
Array when delete is clicked once
["EXCEL 5LB BLACK:2", "EXCEL 5LB BLACK:3", "SATO WHITE LABEL:2", "SATO INK PADS:1"]
Array when delete is clicked twice
["EXCEL 5LB BLACK:2", "EXCEL 5LB BLACK:3", "SATO WHITE LABEL:2"]
Array when delete is clicked third time
["EXCEL 5LB BLACK:2", "EXCEL 5LB BLACK:3"]
Array when delete is clicked fourth time
["EXCEL 5LB BLACK:2"]
The code responsible for this is:
//Delete Function
$(".deleteBtn").click(function(){
console.log(productArray);
var row = this.parentNode.parentNode;
ordertable.deleteRow(row.rowIndex);//remove from the table
productArray.splice(row.rowIndex);//remove from the order array
console.log(productArray);
});
The idea is that the row to be removed from table is the same index as item to be removed from array but this is not working at the moment.
productArray.splice(row.rowIndex,1);
use this splice method to remove
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice
Just a suggestion: You don't need to worry about deleting both in the table and in the array if you use ng-repeat of angular.js
You forgot the howMany argument. That's how many to remove from the array.
array.splice(index , howMany)
So your code should look like
productArray.splice(row.rowIndex, 1);
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice
const candidates = [
{
name: "Amir",
lastName: "Hoxha",
email: "wow#gmail.com",
phone: 198465,
},
{
name: "geogre",
lastName: "horhe",
email: "Horhe#masvidal.com",
phone: 694204,
},
{
name: "Ali",
lastName: "Hamdi",
email: "Dragashi123#gmail.com",
phone: 454784,
},
];
const name = document.getElementById("name").value;
const lastName = document.getElementById("last-name").value;
const email = document.getElementById("email").value;
const phone = document.getElementById("phone").value;
bulidTable(candidates);
function bulidTable(data) {
let myTable = document
.getElementById("my-table")
.getElementsByTagName("tbody")[0];
myTable.innerHTML = "";
for (let i = 0; i < data.length; i++) {
var row = `<tr>
<td>${data[i].name}</td>
<td>${data[i].lastName}</td>
<td>${data[i].email}</td>
<td>${data[i].phone}</td>
<td><button id="btnDelete" >Delete</button>
<button id="btnEdit" onclick="editRow()">Edit</button>
</td>
</tr> `;
myTable.innerHTML += row;
}
}
const myTable = document
.getElementById("my-table")
.getElementsByTagName("tbody")[0];
function addRow() {
// changeToAdd();
if (!valditade()) {
const name = document.getElementById("name").value;
const lastName = document.getElementById("last-name").value;
const email = document.getElementById("email").value;
const phone = document.getElementById("phone").value;
console.log(name, lastName, email, phone);
const obj = {
name: name,
lastName: lastName,
email: email,
phone: phone,
};
candidates.push(obj);
valditade();
bulidTable(candidates);
}
}
// const btnEdit = document.getElementById("btnEdit");
// console.log(btnEdit);
// The Delete Row function
addEventListener("click", (e) => {
if (e.target.id === "btnDelete") {
console.log(e.target.parentElement.parentElement);
const indexToRemove = e.target.parentElement.parentElement.rowIndex - 1;
candidates.splice(indexToRemove, 1);
}
bulidTable(candidates);
});
// The Edit Row function
const btnEdit = document.getElementById("my-button");
console.log(btnEdit);
const btnSave = document.getElementById("btnSave");
console.log(btnSave);
var table = document.getElementById("my-table");
var rIndex;
function editRow() {
for (var i = 1; i < table.rows.length; i++) {
table.rows[i].onclick = function () {
rIndex = this.rowIndex;
console.log(rIndex);
document.getElementById("name").value = this.cells[0].innerHTML;
document.getElementById("last-name").value = this.cells[1].innerHTML;
document.getElementById("email").value = this.cells[2].innerHTML;
document.getElementById("phone").value = this.cells[3].innerHTML;
};
document.getElementById("my-button").style.display = "none";
document.getElementById("btnSave").style.display = "block";
}
}
btnSave.addEventListener("click", (event) => {
console.log(rIndex);
console.log(candidates);
const name = document.getElementById("name").value;
const lastName = document.getElementById("last-name").value;
const email = document.getElementById("email").value;
const phone = document.getElementById("phone").value;
for (var i = 0; i < candidates.length; i++) {
if (i === rIndex - 1) {
candidates[i].name = name;
candidates[i].lastName = lastName;
candidates[i].email = email;
candidates[i].phone = phone;
}
}
event.preventDefault();
document.getElementById("my-button").style.display = "block";
document.getElementById("btnSave").style.display = "none";
console.log(name, lastName, email, phone);
bulidTable(candidates);
});
// Function for clearing the inputs after the add button was clicked on
let btnClear = document.getElementById("my-button");
let inputs = document.querySelectorAll("input");
btnClear.addEventListener("click", () => {
inputs.forEach((input) => (input.value = ""));
});
btnSave.addEventListener("click", () => {
inputs.forEach((input) => (input.value = ""));
});
//This function makes sure that the user has enterted all the required information.
function valditade() {
var isEmpty = false;
const name = document.getElementById("name").value;
const lastName = document.getElementById("last-name").value;
const email = document.getElementById("email").value;
const phone = document.getElementById("phone").value;
if (name === "" && lastName === "" && email === "" && phone === "") {
alert("You Left all the inputs empty");
isEmpty = true;
} else if (name === "") {
alert("Please provide your name");
isEmpty = true;
} else if (lastName === "") {
alert("Please Provide your last name");
isEmpty = true;
} else if (email === "") {
alert("Please provide your Email");
isEmpty = true;
} else if (phone === "") {
alert("Please provide your Phone number");
isEmpty = true;
}
return isEmpty;
}
body {
background: linear-gradient(to left, #333, #333 50%, #eee 75%, #333 75%);
}
table,
th,
td {
font-family: Georgia, "Times New Roman", Times, serif;
}
table#my-table {
border: 1px solid black;
border-radius: 14px;
border-spacing: 0;
}
table#my-table td,
table#my-table {
border-bottom: 1px solid black;
padding: 10px;
}
#table {
margin: 5rem 31rem;
color: white;
font-size: 18px;
}
/* #my-table tr:nth-child(even){
} */
/* #my-table{
border: 1px solid black;
position: static;
width: 20%;
} */
table#my-table tr:last-child > td {
border-bottom: none;
}
#my-button {
display: block;
background-color: #b00b69;
padding: 12px;
font-size: 14px;
color: white;
}
.btnSave{
display: flex;
justify-content: center;
margin: 20px;
padding-top: 15px;
}
#btnSave{
display: none;
background-color: #b00b69;
padding: 12px;
font-size: 14px;
color: white;
}
#my-form {
display: flex;
justify-content: center;
margin: 20px;
padding-top: 15px;
}
#name,
#last-name,
#email,
#phone {
margin: 5px;
padding: 6px;
border-radius: 5px;
font-size: 14px;
}
#name:focus {
background-color: #b00b69;
}
#last-name:focus {
background-color: #b00b69;
}
#email:focus {
background-color: #b00b69;
}
#phone:focus {
background-color: #b00b69;
}
#btnDelete {
color: white;
background-color: black;
padding: 8px;
padding-right: 10px;
margin-top: 5px;
}
#btnEdit {
color: white;
background-color: black;
padding: 8px;
padding-right: 25px;
margin-top: 5px;
}
<!DOCTYPE html>
<html lang="en">
<body>
<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>Table </title>
<link rel="styleSheet" href="style.css">
<script src="table.js" defer></script>
</head>
<body>
<form id="my-form">
<input type="text" id="name" required maxlength="8">
<input type="text" id="last-name" required maxlength="8">
<input type="text" id="email" required maxlength="23" >
<input type="number" id="phone" pattern="/^-?\d+\.?\d*$/"
onKeyPress="if(this.value.length == 9) return false;">
<button id="my-button" onclick="addRow()" value="Add">Add</button>
<button id="btnSave">Save</button>
</form>
<div id="table">
<table id="my-table">
<thead>
<tr>
<th>Name</th>
<th>Last Name</th>
<th>Email</th>
<th>phone</th>
<th>Action</th>
</tr>
</thead>
<tbody id="my-body">
</tbody>
</table>
</body>
</html>
**This is a table that is populated using an array of objects and i add new rows to the table using the push() method and i removed rows using the splice method() **

Categories