Display Javascript Cookies in Table - javascript

I am writing a program which fetches the user's cookies along with their input. I got all the input fields displayed on a dynamic table but couldn't figure out to add the cookie along with it. Also is there any other way to display the table in another page?
<!DOCTYPE html>
<html>
<head>
<title>DATA</title>
<link rel="stylesheet" href="main.css">
</head>
<body>
<div class="container">
<label for="fname">FIRST NAME</label>
<input type="text" name="fname" id="fname">
<label for="lname">LAST NAME</label>
<input type="text" name="lname" id="lname">
<label for="email">EMAIL</label>
<input type="text" name="email" id="email">
<label for="age">AGE</label>
<input type="text" name="age" id="age">
<input type="button" name="button" id="btn" value="Add" onclick="AddRow()">
</div>
<table id="show">
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
<th>Age</th>
<th>Cookies</th>
</tr>
</table>
<script>
function getCookie(name) {
// Split cookie string and get all individual name=value pairs in an array
var cookieArr = document.cookie.split(";");
// Loop through the array elements
for(var i = 0; i < cookieArr.length; i++) {
var cookiePair = cookieArr[i].split("=");
/* Removing whitespace at the beginning of the cookie name
and compare it with the given string */
if(name == cookiePair[0].trim()) {
// Decode the cookie value and return
return decodeURIComponent(cookiePair[1]);
}
}
// Return null if not found
return null;
}
var cookies = document.cookie;
var list1 = [];
var list2 = [];
var list3 = [];
var list4 = [];
var list5 = [];
var n = 1;
var x = 0;
function AddRow(){
var AddRown = document.getElementById('show');
var NewRow = AddRown.insertRow(n);
list1[x] = document.getElementById("fname").value;
list2[x] = document.getElementById("lname").value;
list3[x] = document.getElementById("email").value;
list4[x] = document.getElementById("age").value;
list5[x] = document.getElementById(cookies).value;
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 = list1[x];
cel2.innerHTML = list2[x];
cel3.innerHTML = list3[x];
cel4.innerHTML = list4[x];
cel5.innerHTML = list5[x];
n++;
x++;
}
</script>
</body>
</html>
This is the Error msg I got no matter what I did
Uncaught TypeError: Cannot read properties of null (reading 'value')

Related

How can i get multiple input values with javascript

I tried to code a student manager like below. But when i ran my code in web there seem something error that i dont understanding. I can't get input value from gender and language. When i check console to see something wrong in my code, just a blank.So i dont know why i can't get value when i didn't get any error from console. Because my english skill is not good so I can't explain my mistake. i'm sorry for that. Can someone help me. Thanks firstenter image description here
<table>
<form onsubmit="event.preventDefault();onFormSubmit();" autocomplete="off">
<div id="s1">
<label>Student Name:</label>
<input type="text" placeholder="Input student name"
title="Please fill out this field" id="name" name="name">
</div>
<div id="s2">
<label>Student DOB:</label>
<input type="date" placeholder="dd-mm-yyyy" id="date" name="date">
</div>
<div id="s3">
<label>Student gender:</label>
<input type="radio" id="gender1" class="gender" name="gender">Male
<input type="radio" id="gender2" class="gender" name="gender">Female
</div>
<div id="s4">
<label>Student Language</label>
<input type="checkbox" id="lang1" class="lang" name="lang">English
<input type="checkbox" id="lang2" class="lang" name="lang">Vietnamese
<input type="checkbox" id="lang3" class="lang" name="lang">Japanese
<input type="checkbox" id="lang4" class="lang" name="lang">Chinese
<input type="checkbox" id="lang5" class="lang" name="lang">French
</div>
<div id="s5">
<label>Student Class:</label>
<select id="class" name="class">
<option>C1608G</option>
</select>
Add class
</div>
<button id="bt">Add</button>
</form>
<br><br><br>
<h2><strong>Student List</strong></h2>
<br>
<table id="table" border="1">
<thead>
<tr>
<th>Name</th>
<th>Class</th>
<th>DOB</th>
<th>Gender</th>
<th>Language</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
Here is my javascript code
var selectedRow = null
function onFormSubmit() {
var formData = readFormData();
// check empty row
if (selectedRow == null) {
// Insert New User Record
insertNewRecord(formData);
}
else {
// Update New User Record
updateRecord(formData);
}
// Reset Input Values
resetForm();
}
function readFormData() {
var formData = {};
// Get Values From Input
formData["name"] = document.getElementById("name").value;
formData["class"] = document.getElementById("class").value;
formData["date"] = document.getElementById("date").value;
formData["gender"] = document.getElementsByClassName("gender").value;
formData["lang"] = document.getElementsByClassName("lang").value;
// return Form Data
return formData;
}
function insertNewRecord(data) {
var table = document.getElementById("table").getElementsByTagName('tbody')[0];
var newRow = table.insertRow(table.length);
cell1 = newRow.insertCell(0);
cell1.innerHTML = data.name;
cell2 = newRow.insertCell(1);
cell2.innerHTML = data.class;
cell3 = newRow.insertCell(2);
cell3.innerHTML = data.date;
cell4 = newRow.insertCell(3);
cell4.innerHTML = data.gender;
cell5 = newRow.insertCell(4);
cell5.innerHTML = data.lang;
cell5 = newRow.insertCell(5);
cell5.innerHTML = 'Delete';
}
function updateRecord(formData) {
selectedRow.cells[0].innerHTML = formData.name;
selectedRow.cells[1].innerHTML = formData.class;
selectedRow.cells[2].innerHTML = formData.date;
selectedRow.cells[3].innerHTML = formData.gender;
selectedRow.cells[4].innerHTML = formData.lang;
}
function resetForm() {
document.getElementById("name").value = "";
document.getElementById("class").value = "";
document.getElementById("date").value = "";
document.getElementsByClassName("gender").value = "";
document.getElementsByClassName("lang").value = "";
selectedRow = null;
}
function onDelete(td) {
if (confirm('Are you sure to delete this record ?')) {
row = td.parentElement.parentElement;
document.getElementById("table").deleteRow(row.rowIndex);
resetForm();
}
}
function updateRecord(formData) {
selectedRow.cells[0].innerHTML = formData.name;
selectedRow.cells[1].innerHTML = formData.class;
selectedRow.cells[2].innerHTML = formData.data;
selectedRow.cells[3].innerHTML = formData.gender;
selectedRow.cells[4].innerHTML = formData.lang;
}
Two major problems you have in your code.
Your radio/checkboxes need to have values - your code cannot infer the text next to them as the value (without some additional coding and anyways that's not the right way to do it)
To check which radio is selected, you can use querySelector and the ? flag. Here's what it looks like in your code after I've added it:
formData["gender"] = document.querySelector(".gender:checked")?.value || '';
Which is: document.querySelector(".gender:checked") finds the item with the class name 'gender' that is checked (the psuedo class :checked does that). If it doesn't exist (if there isn't an element with that class name or none of them are checked), the ? flag captures that and instead a blank value is used. (Otherwise it might throw an error or be undefined)
To get all the checked checkboxes, you can use this kind of structure:
formData["lang"] = [];
// creates the array
document.querySelectorAll(".lang:checked").forEach(item => formData["lang"].push(item.value));
// loops through each checked checkbox and gets it's value, adding it to the array
formData["lang"] = formData["lang"].join(', ')
// this converts your array into a list that is comma separated. This line is optional because javascript will show your array as a comma separated list anyways
var selectedRow = null
function onFormSubmit() {
var formData = readFormData();
// check empty row
if (selectedRow == null) {
// Insert New User Record
insertNewRecord(formData);
} else {
// Update New User Record
updateRecord(formData);
}
// Reset Input Values
resetForm();
}
function readFormData() {
var formData = {};
// Get Values From Input
formData["name"] = document.getElementById("name").value;
formData["class"] = document.getElementById("class").value;
formData["date"] = document.getElementById("date").value;
formData["gender"] = document.querySelector(".gender:checked")?.value || '';
formData["lang"] = [];
document.querySelectorAll(".lang:checked").forEach(item => formData["lang"].push(item.value));
formData["lang"] = formData["lang"].join(', ')
// return Form Data
return formData;
}
function insertNewRecord(data) {
var table = document.getElementById("table").getElementsByTagName('tbody')[0];
var newRow = table.insertRow(table.length);
cell1 = newRow.insertCell(0);
cell1.innerHTML = data.name;
cell2 = newRow.insertCell(1);
cell2.innerHTML = data.class;
cell3 = newRow.insertCell(2);
cell3.innerHTML = data.date;
cell4 = newRow.insertCell(3);
cell4.innerHTML = data.gender;
cell5 = newRow.insertCell(4);
cell5.innerHTML = data.lang;
cell5 = newRow.insertCell(5);
cell5.innerHTML = 'Delete';
}
function updateRecord(formData) {
selectedRow.cells[0].innerHTML = formData.name;
selectedRow.cells[1].innerHTML = formData.class;
selectedRow.cells[2].innerHTML = formData.date;
selectedRow.cells[3].innerHTML = formData.gender;
selectedRow.cells[4].innerHTML = formData.lang;
}
function resetForm() {
document.getElementById("name").value = "";
document.getElementById("class").value = "";
document.getElementById("date").value = "";
document.getElementsByClassName("gender").value = "";
document.getElementsByClassName("lang").value = "";
selectedRow = null;
}
function onDelete(td) {
if (confirm('Are you sure to delete this record ?')) {
row = td.parentElement.parentElement;
document.getElementById("table").deleteRow(row.rowIndex);
resetForm();
}
}
function updateRecord(formData) {
selectedRow.cells[0].innerHTML = formData.name;
selectedRow.cells[1].innerHTML = formData.class;
selectedRow.cells[2].innerHTML = formData.data;
selectedRow.cells[3].innerHTML = formData.gender;
selectedRow.cells[4].innerHTML = formData.lang;
}
<form onsubmit="event.preventDefault();onFormSubmit();" autocomplete="off">
<div id="s1">
<label>Student Name:</label>
<input type="text" placeholder="Input student name" title="Please fill out this field" id="name" name="name">
</div>
<div id="s2">
<label>Student DOB:</label>
<input type="date" placeholder="dd-mm-yyyy" id="date" name="date">
</div>
<div id="s3">
<label>Student gender:</label>
<input type="radio" id="gender1" class="gender" name="gender" value="Male">Male
<input type="radio" id="gender2" class="gender" name="gender" value="Female">Female
</div>
<div id="s4">
<label>Student Language</label>
<input type="checkbox" id="lang1" class="lang" name="lang" value="English">English
<input type="checkbox" id="lang2" class="lang" name="lang" value="Vietnamese">Vietnamese
<input type="checkbox" id="lang3" class="lang" name="lang" value="Japanese">Japanese
<input type="checkbox" id="lang4" class="lang" name="lang" value="Chinese">Chinese
<input type="checkbox" id="lang5" class="lang" name="lang" value="French">French
</div>
<div id="s5">
<label>Student Class:</label>
<select id="class" name="class">
<option>C1608G</option>
</select>
Add class
</div>
<button id="bt">Add</button>
</form>
<br><br><br>
<h2><strong>Student List</strong></h2>
<br>
<table id="table" border="1">
<thead>
<tr>
<th>Name</th>
<th>Class</th>
<th>DOB</th>
<th>Gender</th>
<th>Language</th>
</tr>
</thead>
<tbody>
</tbody>
</table>

How to display radio and checkbox values in table using javascript?

When I click display button it displays name and age but gender and checkbox is incorrect it displays first value only. I want to display which i select.
radio data and checkbox data should display.
(function setup() {
"use strict";
var NameElem = document.getElementById("name");
var genderElem = document.getElementById("gender");
var ageElem = document.getElementById("age");
var languageElem = document.getElementById("language");
var tableElem = document.getElementById("table");
document.getElementById("display").addEventListener("click", function() {
var newRow = tableElem.insertRow(-1);
var newCell = newRow.insertCell(0);
var newText = document.createTextNode(NameElem.value);
newCell.appendChild(newText);
newCell = newRow.insertCell(1);
newText = document.createTextNode(genderElem.value);
newCell.appendChild(newText);
newCell = newRow.insertCell(2);
newText = document.createTextNode(ageElem.value);
newCell.appendChild(newText);
newCell = newRow.insertCell(3);
newText = document.createTextNode(languageElem.value);
[newCell.appendChild][1](newText);
NameElem.value = "";
genderElem.value = "";
ageElem.value = "";
languageElem.value = "";
tableElem.value = "";
});
})();
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.6.0/dist/css/bootstrap.min.css" integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" crossorigin="anonymous">
<div class="container">
<br>
<br>
<h3 class="text-center">Display answers of form fill in inside a table</h3>
<br>
<br>
<form>
<div class="form-group">
<label>First Name</label>
<input id="name" class="form-control form-control-sm" />
</div>
<div class="form-group">
<label>Age</label>
<input id="age" class="form-control form-control-sm" />
</div>
<div class="form-group">
Gender:<input type="radio" name="male" id="gender" value="male">Male
<input type="radio" name="female" id="gender" value="female">
<label for="female">Female</label>
</div>
<div class="form-group">
<label>Language</label>
<input type="checkbox" id="language" name="malayalam" value="Malayalam">Malayalam
<input type="checkbox" id="language" name="english" value="English">English
<input type="checkbox" id="language" name="hindi" value="Hindi">Hindi
</div>
<button type="button" id="display" class="btn btn-sm btn-primary">Display</button>
</form>
<br>
<br>
<table class="table border" id="table">
<tr>
<th>Name</th>
<th>Gender</th>
<th>Age</th>
<th>Language</th>
</tr>
</table>
<script type="text/javascript" src="form.js"></script>
</div>
Well, the code does exactly what you asked for.
var genderElem = document.getElementById("gender");
// returns the element with ID "gender"
You are mixing name attribute with ID.
An ID must always be unique : a web page can't contain several elements with the same ID.
What you are looking for is the checked input of name "gender".
var genderValue = '';
document.querySelectorAll('input[name=gender]').forEach((e)=>{
if (e.checked==true) { genderValue = e.value; }
});
Couple of mistakes you did:
Radio buttons and Checkboxes should always have same name if they are in the same group.
Always keep ID different, its bad practice to keep ID same for multiple elements.
When you are trying to get the value of Radio button or Checkboxes, fetch it using getElementsByName and run a loop over all on click of display button not outside.
Safer side and to reduce the LOC, give your form an ID and reset the form on submit using formId.reset() method. (in your code I have given form an id myForm so I have added myForm.reset(); at the end of the code on submit method)
See the Snippet below:
(function setup() {
"use strict";
var myForm = document.getElementById("myForm");
var NameElem = document.getElementById("name");
var ageElem = document.getElementById("age");
var genderElem = document.getElementsByName('gender');
var languageElem = document.getElementsByName("language");
var tableElem = document.getElementById("table");
var selectedGender = '';
var selectedLanguages = [];
document.addEventListener("click", function(event){
if(event.target.classList.contains("delete")){
var row = event.target.parentNode.parentNode;
row.parentNode.removeChild(row);
}
});
document.getElementById("display").addEventListener("click", function() {
for(var i = 0; i < genderElem.length; i++) {
if(genderElem[i].checked)
selectedGender = genderElem[i].value;
}
for(var i = 0; i < languageElem.length; i++) {
if(languageElem[i].checked)
selectedLanguages.push(languageElem[i].value);
}
var newRow = tableElem.insertRow(-1);
var newCell = newRow.insertCell(0);
var newText = document.createTextNode(NameElem.value);
newCell.appendChild(newText);
newCell = newRow.insertCell(1);
newText = document.createTextNode(selectedGender);
newCell.appendChild(newText);
newCell = newRow.insertCell(2);
newText = document.createTextNode(ageElem.value);
newCell.appendChild(newText);
newCell = newRow.insertCell(3);
newText = document.createTextNode(selectedLanguages.toString());
newCell.appendChild(newText);
newCell = newRow.insertCell(4);
var deleteBtn = document.createElement("button");
deleteBtn.textContent = "Delete";
deleteBtn.classList.add("delete");
newCell.appendChild(deleteBtn);
/*NameElem.value = "";
genderElem.value = "";
ageElem.value = "";
languageElem.value = "";
tableElem.value = "";*/
myForm.reset();
selectedGender = "";
selectedLanguages = [];
});
})();
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.6.0/dist/css/bootstrap.min.css" integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" crossorigin="anonymous">
<div class="container">
<br>
<br>
<h3 class="text-center">Display answers of form fill in inside a table</h3>
<br>
<br>
<form id="myForm">
<div class="form-group">
<label>First Name</label>
<input id="name" class="form-control form-control-sm" />
</div>
<div class="form-group">
<label>Age</label>
<input id="age" class="form-control form-control-sm" />
</div>
<div class="form-group">
Gender:<input type="radio" name="gender" id="male" value="Male">
<label for="male">Male</label>
<input type="radio" name="gender" id="female" value="Female">
<label for="female">Female</label>
</div>
<div class="form-group">
<label>Language</label>
<input type="checkbox" id="malayalam" name="language" value="Malayalam">Malayalam
<input type="checkbox" id="english" name="language" value="English">English
<input type="checkbox" id="hindi" name="language" value="Hindi">Hindi
</div>
<button type="button" id="display" class="btn btn-sm btn-primary">Display</button>
</form>
<br>
<br>
<table class="table border" id="table">
<tr>
<th>Name</th>
<th>Gender</th>
<th>Age</th>
<th>Language</th>
<th>Action</th>
</tr>
</table>
<script type="text/javascript" src="form.js"></script>
</div>
UPDATE 1 : Added delete row feature
document.addEventListener("click", function(event){
if(event.target.classList.contains("delete")){
var row = event.target.parentNode.parentNode;
row.parentNode.removeChild(row);
}
});
newCell = newRow.insertCell(4);
var deleteBtn = document.createElement("button");
deleteBtn.textContent = "Delete";
deleteBtn.classList.add("delete");
newCell.appendChild(deleteBtn);

problem with loop in google web script app

Good night, how are you?
I created a form, that before the information is inserted in the spreadsheets, the data goes to an HTML table, where you can delete or edit it before sending the data, so far so good,
the problem that I tried to create a loop to go clicking several times until all the data in the table ends, the problem that when I run the loop there is an error that all the data cannot go to the spreadsheet.
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
</head>
<body id="pagina">
<br>
<div class= "container">
<div class="row">
<div class="input-field col s12 l4">
<input id="saiDesc" type="text" class="autocomplete" class="validate" required>
<!--<label for="saiDesc" class="active">DESCRIÇÃO DO PRODUTO</label>-->
<label>PRODUTO</label><label class="validation-error hide" id="fullNameValidationError">This field is required.</label>
</div>
<div class="input-field col s6 l1">
<input id="saiCod" type="text" class="validate" required>
<label for="saiCod">CÓDIGO</label>
</div>
<div class="input-field col s6 l1">
<input id="saiQtd" type="text" class="validate" required>
<label for="saiQtd">QUANTIDADE</label>
</div>
<div class="input-field col s6 l1">
<input id="saiVlr" type="text" class="validate" required>
<label for="saiVlr">VALOR</label>
</div>
<div class="input-field col s6 l1">
<input id="saiTotal" type="text" class="validate" required>
<label for="saiTotal">VALOR TOTAL</label>
</div>
<div class="input-field col s12 l4">
<input id="saiObs" type="text" class="validate" required>
<label for="saiObs">OBSERVAÇÃO</label>
</div>
</div> <!-- Fecha Row -->
<div class="row">
<div class="input-field col s6 l1">
<input disabled id="saiTotalizador" type="text">
<label for="saiTotalizador">TOTAL</label>
</div>
<div class="center-align">
<button id="teste" onclick="onFormSubmit(); sum();" class="left waves-effect waves-light btn red darken-2"><i class="material-icons left">add</i>ADD</button>
<button id="teste" onclick="preencher();" class="center waves-effect waves-light btn blue darken-2"><i class="material-icons left">add</i>preencher</button>
<button id="registrar2" class="right waves-effect waves-light btn blue-grey darken-2"><i class="material-icons left">send</i>REGISTER ALL</button>
</div> <!-- Fecha Row -->
</div>
<hr>
<!--<div class="form-action-buttons">
<input type="submit" onclick="onFormSubmit();"value="Enviar">
</div>-->
<td>
<table class="list" id="employeeList">
<thead>
<tr>
<th>PRODUTO</th>
<th>CÓD INT.</th>
<th>QUANT.</th>
<th>VALOR<br/>UNIT.</th>
<th>VALOR<br/>TOTAL</th>
<th>OBS.</th>
<th></th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div> <!-- Fecha Conatainer -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
<script>
var selectedRow = null
function onFormSubmit() {
if (validate()) {
var formData = readFormData();
if (selectedRow == null)
insertNewRecord(formData);
else
updateRecord(formData);
resetForm();
}
}
function readFormData() {
var formData = {};
formData["saiDesc"] = document.getElementById("saiDesc").value;
formData["saiCod"] = document.getElementById("saiCod").value;
formData["saiQtd"] = document.getElementById("saiQtd").value;
formData["saiVlr"] = document.getElementById("saiVlr").value;
formData["saiTotal"] = document.getElementById("saiTotal").value;
formData["saiObs"] = document.getElementById("saiObs").value;
return formData;
}
function insertNewRecord(data) {
var table = document.getElementById("employeeList").getElementsByTagName('tbody')[0];
var newRow = table.insertRow(table.length);
cell1 = newRow.insertCell(0);
cell1.innerHTML = data.saiDesc;
cell2 = newRow.insertCell(1);
cell2.innerHTML = data.saiCod;
cell3 = newRow.insertCell(2);
cell3.innerHTML = data.saiQtd;
cell4 = newRow.insertCell(3);
cell4.innerHTML = data.saiVlr;
cell5 = newRow.insertCell(4);
cell5.innerHTML = data.saiTotal;
cell6 = newRow.insertCell(5);
cell6.innerHTML = data.saiObs;
cell6 = newRow.insertCell(6);
cell6.innerHTML = `<a onClick="onEdit(this)" id="testeEdit" class="btn-floating blue"><i class="material-icons left">edit</i></a>
<a onClick="onDelete(this)" id="testedelete" class="btn-floating red" ><i class="material-icons left">delete</i></a>`;
}
function resetForm() {
document.getElementById("saiDesc").value = "";
document.getElementById("saiCod").value = "";
document.getElementById("saiQtd").value = "";
document.getElementById("saiVlr").value = "";
document.getElementById("saiTotal").value = "";
document.getElementById("saiObs").value = "";
selectedRow = null;
}
function onEdit(td) {
selectedRow = td.parentElement.parentElement;
document.getElementById("saiDesc").value = selectedRow.cells[0].innerHTML;
document.getElementById("saiCod").value = selectedRow.cells[1].innerHTML;
document.getElementById("saiQtd").value = selectedRow.cells[2].innerHTML;
document.getElementById("saiVlr").value = selectedRow.cells[3].innerHTML;
document.getElementById("saiTotal").value = selectedRow.cells[4].innerHTML;
document.getElementById("saiObs").value = selectedRow.cells[5].innerHTML;
M.updateTextFields();
}
function updateRecord(formData) {
selectedRow.cells[0].innerHTML = formData.saiDesc;
selectedRow.cells[1].innerHTML = formData.saiCod;
selectedRow.cells[2].innerHTML = formData.saiQtd;
selectedRow.cells[3].innerHTML = formData.saiVlr;
selectedRow.cells[4].innerHTML = formData.saiTotal;
selectedRow.cells[5].innerHTML = formData.saiObs;
}
function onDelete(td) {
// if (confirm('Are you sure to delete this record ?')) {
row = td.parentElement.parentElement;
document.getElementById("employeeList").deleteRow(row.rowIndex);
resetForm();
//}
}
function validate() {
isValid = true;
if (document.getElementById("saiDesc").value == "") {
isValid = false;
document.getElementById("fullNameValidationError").classList.remove("hide");
} else {
isValid = true;
if (!document.getElementById("fullNameValidationError").classList.contains("hide"))
document.getElementById("fullNameValidationError").classList.add("hide");
}
return isValid;
}
function sum() {
var table = document.getElementById("employeeList");
var sumVal = 0;
for(var i = 1; i < table.rows.length; i++)
sumVal = sumVal + parseFloat(table.rows[i].cells[4].innerHTML.replace(",", "."));
document.getElementById("saiTotalizador").value = sumVal;
M.updateTextFields();
}
function preencher(){
document.getElementById("saiDesc").value = Math.floor((Math.random() * 10) + 1);
document.getElementById("saiCod").value = Math.floor((Math.random() * 10) + 1);
document.getElementById("saiQtd").value = Math.floor((Math.random() * 10) + 1);
document.getElementById("saiVlr").value = Math.floor((Math.random() * 10) + 1);
document.getElementById("saiTotal").value = Math.floor((Math.random() * 10) + 1);
document.getElementById("saiObs").value = Math.floor((Math.random() * 10) + 1);
M.updateTextFields();
}
document.getElementById("registrar2").addEventListener("click",registrarTudo2);
function registrarTudo2(){
var linhas = employeeList.querySelectorAll("tr").length-1;
for (var i = 0; i < linhas; i ++){
document.getElementById("testeEdit").click();
var userInfo = {};
userInfo.saiDesc = document.getElementById("saiDesc").value;
userInfo.saiCod = document.getElementById("saiCod").value;
userInfo.saiQtd = document.getElementById("saiQtd").value;
userInfo.saiVlr = document.getElementById("saiVlr").value;
userInfo.saiTotal = document.getElementById("saiTotal").value;
userInfo.saiObs = document.getElementById("saiObs").value;
google.script.run.registrar(userInfo);
document.getElementById("testedelete").click();
};
};
</script>
</body>
</html>
Gas:
function registrar(userInfo){
var ss = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/1XVICy3RPRRUPtyXtgSi9Ab7iaOOODM6zkJ3Fq4T-h_M/edit#gid=0");
var ws = ss.getSheetByName("Página1");
ws.appendRow([userInfo.saiDesc,
userInfo.saiCod,
userInfo.saiQtd,
userInfo.saiVlr,
userInfo.saiTotal,
userInfo.saiObs
]);
}
note: if I take the loop and click 2x, 3x, 15x, the register button runs the script right.
just with the loop it gives the error.
How about this modification?
Modification points:
I think that the reason of your issue is that google.script.run is run with the asynchronous process. But in your case, the method of appendRow is used in the for loop at Google Apps side. In this case, the process cost will be high. So in this answer, I would like to propose the following flow.
Retrieve all values of userInfo and put them to an array.
Send the array to Google Apps Script side using google.script.run.
At Google Apps Script side, convert the array for putting to Spreadsheet and put the values.
When above points are reflected to your script, it becomes as follows.
Modified script:
HTML&Javascript side:
Please modify registrarTudo2() as follows.
function registrarTudo2(){
var values = []; // Added
var linhas = employeeList.querySelectorAll("tr").length-1;
for (var i = 0; i < linhas; i ++){
document.getElementById("testeEdit").click();
var userInfo = {};
userInfo.saiDesc = document.getElementById("saiDesc").value;
userInfo.saiCod = document.getElementById("saiCod").value;
userInfo.saiQtd = document.getElementById("saiQtd").value;
userInfo.saiVlr = document.getElementById("saiVlr").value;
userInfo.saiTotal = document.getElementById("saiTotal").value;
userInfo.saiObs = document.getElementById("saiObs").value;
values.push(userInfo); // Added
document.getElementById("testedelete").click();
}
google.script.run.registrar(values); // Added
}
Google Apps Script side:
Please modify registrar() as follows.
function registrar(values){
var ss = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/###/edit#gid=0");
var ws = ss.getSheetByName("Página1");
var v = values.map(userInfo => [userInfo.saiDesc,userInfo.saiCod,userInfo.saiQtd,userInfo.saiVlr,userInfo.saiTotal,userInfo.saiObs]); // Added
ws.getRange(ws.getLastRow() + 1, 1, v.length, v[0].length).setValues(v); // Added
}
Please set the URL of your Spreadsheet to SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/###/edit#gid=0").
References:
Class google.script.run
setValues(values)

Issue Cloning Form Fields Within Table with Javascript

In the code below it works great to clone the table, but it doesn't go deep enough to rename the inputs of each form field in the table. For example Attendee1, Attendee2, Attendee3 etc.
Is there a way instead of just grabbing NewEl.children a way to just find all the input elements within the table then rename them?
I am not trying to add a row, I need to clone the entire table.
Any help you all out there in cyberland can give will be greatly appreciated.
<form name="EditRoster" method="post" action="DoRoster.php">
<table id="RosterTbl" cellspacing="0" cellpadding="2">
<tr style="text-align:left;vertical-align:top;">
<td><b>Name</b>:</td>
<td>
<input type="text" name="Attendee" value="" size="25" onclick="alert(this.name)">
</td>
<td><b>Paid</b>:</td>
<td>
<input type="checkbox" name="Paid" value="Yes" size="25">
</td>
</tr>
<tr style="text-align:left;vertical-align:top;">
<td><b>Email</b>:</td>
<td>
<input type="text" name="Email" value="" size="25">
</td>
<td><b>Paid When</b>:</td>
<td>
<input type="text" name="PaidWhen" value="" size="10">
</td>
</tr>
</table>
<div style="padding:5px;">
<input type="hidden" name="NumStudents" value="0">
<input type="button" name="AddPersonButton" value="Add Person" onclick="CloneElement('RosterTbl','NumStudents');">
</div>
</form>
<script language="javascript">
var TheForm = document.forms.EditRoster;
function CloneElement(ElToCloneId, CounterEl) {
var CloneCount = TheForm[CounterEl].value;
CloneCount++;
TheForm[CounterEl].value = CloneCount;
var ElToClone = document.getElementById(ElToCloneId);
var NewEl = ElToClone.cloneNode(true);
NewEl.id = ElToCloneId + CloneCount;
NewEl.style.display = "block";
var NewField = NewEl.children;
for (var i = 0; i < NewField.length; i++) {
var InputName = NewField[i].name;
if (InputName) {
NewField[i].name = InputName + CloneCount;
}
var insertHere = document.getElementById(ElToCloneId);
insertHere.parentNode.insertBefore(NewEl, insertHere);
}
}
</script>
Looked like you were on the right track, but I think you were taking a few extra steps, so I think I simplified it ;)
One thing you were missing was that the value of NumStudents is returned as a string so you have to call parseInt() on it.
var theForm = document.forms.EditRoster;
function insertAfter(referenceNode, newNode) {
referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
}
function CloneElement(cloneID, counterName) {
var clone = document.getElementById(cloneID);
var newClone = clone.cloneNode(true);
var counter = theForm[counterName].value = parseInt(theForm[counterName].value) + 1;
// Update the form ID
newClone.id = newClone.id + counter;
// Update the child Names
var items = newClone.getElementsByTagName("*");
for (var i = 0; i < items.length; i++) {
if (items[i].name != null)
items[i].name = items[i].name + counter;
}
insertAfter(clone, newClone);
}
Here's a working copy on jsFiddle.
P.s. I wasn't sure if you wanted the new fields clearing so I left them.

JavaScript Renaming Form Image Input Name

I am developing this for use in Internet Explorer 8 (because at work we have to use it). I have a page that has a table withing a form. The table has a button to "clone" rows, "AddScheduleRow()". That part works good. Each row has a button to delete that row "DeleteRow(r)". That part works well too. I also have a script to rename/renumber each row, "RenumberRows()". It almost works good. I can rename the text fields (for example what was previously StartDate3 now becomes StartDate2). However, in each row is an input that is type="image" and it is named like you should with any input. The name of it is "StartDateCal". The problem is that during the renaming process, when it hits the image input (TheForm.StartDateCal[i].name = "StartDateCal" + TempCounter;), I get a JavaScript error "'TheForm.StartDateCal' is null or not an object". I cannot figure this one out and it's standing in the way of moving on.
What can I do to try to rename an < input type = image /> ?
Below is the necessary code:
HTML
<html>
<head>
</head>
<body>
<form name="UpdateSchedule" method="post" action="DoSchedule.asp">
<input type="hidden" name="NumRows" value="0">
<input type="hidden" name="RowsAdded" value="0">
<table id="ClassScheduleTable">
<tr id="ScheduleRow" style="display:none;">
<td>
<input type="text" name="RowNum" value="0" size="1" onclick="alert(this.name)">
</td>
<td>
<b>Start Date</b> <input type="text" name="StartDate" value="" onclick="alert(this.name);" size="8">
<input type="image" name="StartDateCal" src="http://www.CumminsNorthwest.com/ATT/Img/Calendar3.png" style="border-style:none;" onClick="alert('name = ' + this.name);return false;">
</td>
<td>
<input type="button" value="Del." name="DelRow" class="subbuttonb" onclick="DeleteRow(this);">
</td>
</tr>
<tr>
<td colspan="3" style="text-align:right">
<input type="button" value="Add Class Date" class="SubButton" onclick="AddScheduleRow();">
</td>
</tr>
</table>
</form>
</body>
<script language="JavaScript">
JS
var TheForm = document.forms.UpdateSchedule;
var NumRows =0;
var RowsAdded =0;
function AddScheduleRow(){
NumRows++;
TheForm.NumRows.value = NumRows;
RowsAdded++;
TheForm.RowsAdded.value = RowsAdded;
var TableRowId = "ScheduleRow";
var RowToClone = document.getElementById(TableRowId);
var NewTableRow = RowToClone.cloneNode(true);
NewTableRow.id = TableRowId + NumRows ;
NewTableRow.style.display = "table-row";
var NewField = NewTableRow.children;
for (var i=0;i<NewField.length;i++){
var TheInputFields = NewField[i].children;
for (var x=0;x<TheInputFields.length;x++){
var InputName = TheInputFields[x].name;
if (InputName){
TheInputFields[x].name = InputName + NumRows;
//alert(TheInputFields[x].name);
}
var InputId = TheInputFields[x].id;
if (InputId){
TheInputFields[x].id = InputId + NumRows;
//alert(TheInputFields[x].id);
}
}
}
var insertHere = document.getElementById(TableRowId);
insertHere.parentNode.insertBefore(NewTableRow,insertHere);
RenumberRows();
}
AddScheduleRow();
function DeleteRow(r){
var i=r.parentNode.parentNode.rowIndex;
document.getElementById("ClassScheduleTable").deleteRow(i);
NumRows--;
TheForm.NumRows.value = NumRows;
RenumberRows();
}
function RenumberRows(){
var TempCounter = 0;
for (var i=0;i<=RowsAdded;i++){
if (TheForm.RowNum[i]){
TempCounter++;
TheForm.RowNum[i].name = "RowNum" + TempCounter;
TheForm.RowNum[i].value = TempCounter;
TheForm.StartDate[i].name = "StartDate" + TempCounter;
TheForm.StartDateCal[i].name = "StartDateCal" + TempCounter;
}
}
}
</script>
</html>
might be to do with your DTD,
try HTML4 Strict:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
You can use
document.getElementsByName('StartDateCal')[i].name = "StartDateCal" + TempCounter;
instead of
TheForm.StartDateCal[i].name = "StartDateCal" + TempCounter;

Categories