Report values in cascading dropdowns in Web App - javascript

I am a beginner in development and I am currently working on the development of a web app under Google Apps Script.
This one is composed of two parts:
a form so that different users can make requests
a home page where you can see in a table all the requests that have been made.
These two pages work perfectly. However, I would like to add the possibility to edit and/or delete a request from the table on the home page. So I added an "edit" and "delete" button in my table for each row.
When I click on the "edit" button, I save the id of the selected request in a global variable with the Apps Script and then I am redirected to the form to edit my request.
This is the edit's button :
<button type="button" class="btn btn-outline-dark classButtonEdition" onClick="editDemande();">Éditer</button>
This is the function launched on click event :
function editDemande(){
// Récupère l'id de la demande à éditer et transfère celui-ci dans une variable globale persistante
var id = event.srcElement.id;
google.script.run.withSuccessHandler().transfertIdDemande(id);
// Ouvre le formulaire "Édition de la demande"
var url = document.getElementById("url").value;
var link = document.createElement('a');
link.href = url+"?page=Édition demande";
link.id = 'linkURL';
document.body.appendChild(link);
document.getElementById("linkURL").click();
}
And this is the apps script's function that allows me to register my id :
function transfertIdDemande(id){
PropertiesService.getScriptProperties().setProperty("idDemande",id);
}
When the form is fully loaded, a function is executed using this code:
document.addEventListener("DOMContentLoaded",changeValuesOfEditForm);
And this is the function :
function changeValuesOfEditForm(){
google.script.run.withSuccessHandler(modifyValues).getIdDemande();
}
With this, I can automatically fill in the form fields corresponding to the request id :
function modifyValues(id){
// Modification de l'Id
document.getElementById("idDemande").value = id;
document.getElementById("idDemande").readOnly = true;
// Secteur
google.script.run.withSuccessHandler(secteur => {
document.getElementById("secteur").value = secteur;
}).getSecteurEdit(id);
// Zone
// google.script.run.withSuccessHandler(zone => {
// document.getElementById("zone").value = zone;
// }).getZoneEdit(id);
// Modification de la description
google.script.run.withSuccessHandler(description => {
document.getElementById("description").value = description;
}).getDescriptionEdit(id);
// Modification de l'équipement stratégique
google.script.run.withSuccessHandler(equipementStratEdit => {
document.getElementById("equipementStrategique").value = equipementStratEdit;
}).getEquipementEdit(id);
// Modification de l'intervention possible en prod
google.script.run.withSuccessHandler(interventionProdEdit => {
document.getElementById("interventionProd").value = interventionProdEdit;
}).getInterventionEdit(id);
// Modification de la disponibilité de la zone
google.script.run.withSuccessHandler(dispoZone => {
document.getElementById("disponibiliteZone").value = dispoZone;
}).getDispoZoneEdit(id);
// Modification du délai
google.script.run.withSuccessHandler(delai => {
if (delai === "Inférieur à 2 mois" || delai === "Inférieur à 1 mois" ||
delai === "Inférieur à 2 semaines" || delai === "Inférieur à 1 semaine"){
document.getElementById("delai").value = delai;
}
else{
document.getElementById("delai").value = "Demande urgente";
document.getElementById("divDemandeUrgente").style.display = "block";
document.getElementById("dateDemandeUrgente").value = delai;
}
}).getDelaiEdit(id);
}
There're apps script's function in link with this part of code :
function getSecteurEdit(id){
const classeur = SpreadsheetApp.getActiveSpreadsheet();
const feuille = classeur.getSheetByName("Demandes");
var tDemandes = feuille.getRange("A3:B").getValues().filter(d=>d[0] != "");
var secteurId = "";
for (let i = 0; i < tDemandes.length; i ++){
if (tDemandes[i][0] === id){
secteurId = tDemandes[i][1];
break;
}
}
return secteurId;
}
function getDescriptionEdit(id){
const classeur = SpreadsheetApp.getActiveSpreadsheet();
const feuille = classeur.getSheetByName("Demandes");
var tDemandes = feuille.getRange("A3:J").getValues().filter(d=>d[0] != "");
var descriptionId = "";
for (let i = 0; i < tDemandes.length; i ++){
if (tDemandes[i][0] === id){
descriptionId = tDemandes[i][9];
break;
}
}
return descriptionId;
}
function getEquipementEdit(id){
const classeur = SpreadsheetApp.getActiveSpreadsheet();
const feuille = classeur.getSheetByName("Demandes");
var tDemandes = feuille.getRange("A3:F").getValues().filter(d=>d[0] != "");
var equipementId = "";
for (let i = 0; i < tDemandes.length; i ++){
if (tDemandes[i][0] === id){
equipementId = tDemandes[i][5];
break;
}
}
return equipementId;
}
function getInterventionEdit(id){
const classeur = SpreadsheetApp.getActiveSpreadsheet();
const feuille = classeur.getSheetByName("Demandes");
var tDemandes = feuille.getRange("A3:G").getValues().filter(d=>d[0] != "");
var interventionId = "";
for (let i = 0; i < tDemandes.length; i ++){
if (tDemandes[i][0] === id){
interventionId = tDemandes[i][6];
break;
}
}
return interventionId;
}
function getDispoZoneEdit(id){
const classeur = SpreadsheetApp.getActiveSpreadsheet();
const feuille = classeur.getSheetByName("Demandes");
var tDemandes = feuille.getRange("A3:H").getValues().filter(d=>d[0] != "");
var dispoZoneId = "";
for (let i = 0; i < tDemandes.length; i ++){
if (tDemandes[i][0] === id){
dispoZoneId = tDemandes[i][7];
break;
}
}
return dispoZoneId;
}
function getDelaiEdit(id){
const classeur = SpreadsheetApp.getActiveSpreadsheet();
const feuille = classeur.getSheetByName("Demandes");
var tDemandes = feuille.getRange("A3:I").getValues().filter(d=>d[0] != "");
var dispoZoneId = "";
for (let i = 0; i < tDemandes.length; i ++){
if (tDemandes[i][0] === id){
if(isValidDate(tDemandes[i][8])){
dispoZoneId = Utilities.formatDate(new Date(tDemandes[i][8]),"GMT+1","yyyy-MM-dd");
break;
}
else{
dispoZoneId = tDemandes[i][8];
break;
}
}
}
return dispoZoneId;
}
All my fields are automatically filled in except for the drop-down menus. Since they are cascaded, this does not work. I tried to include a google.script.run in another google.script.run but it should not be allowed.
This is my apps script's function allowed me to show values of each dropdown after clicking :
function getSecteurs(){
const classeur = SpreadsheetApp.getActiveSpreadsheet();
const feuille = classeur.getSheetByName('BDD');
var secteurs = feuille.getRange('A2:A').getValues().filter(d =>d[0] !== '');
var tSecteurs = [];
secteurs.forEach(function(x){
if(tSecteurs.indexOf(x[0]) === -1){
tSecteurs.push(x[0])
}
});
return tSecteurs.map(d => '<option>' + d + '</option>').join('');
}
function getZones(secteur){
const classeur = SpreadsheetApp.getActiveSpreadsheet();
const feuille = classeur.getSheetByName('BDD');
var secteursZones = feuille.getRange('A2:B').getValues().filter(d =>d[0] !== '');
var zones = [["Choisissez..."]], tZones = [];
for (let i = 0; i < secteursZones.length; i ++){
if (secteursZones[i][0] == secteur){
zones.push([secteursZones[i][1]]);
}
}
zones.push(["Non définie"]);
zones.forEach(function(x){
if(tZones.indexOf(x[0]) === -1){
tZones.push(x[0])
}
});
var selectZones = [];
for (let i = 0; i < tZones.length; i ++){
if(tZones[i] === "Choisissez..."){
selectZones.push('<option disabled selected>Choisissez...</option>');
}
else{
selectZones.push('<option>' + tZones[i] + '</option>');
}
}
return selectZones.join('');
}
function getSalles(secteur,zone){
const classeur = SpreadsheetApp.getActiveSpreadsheet();
const feuille = classeur.getSheetByName('BDD');
var zonesSalles = feuille.getRange('A2:C').getValues().filter(d =>d[0] !== '');
var salles = [["Choisissez..."]], tSalles = [];
for (let i = 0; i < zonesSalles.length; i ++){
if (zonesSalles[i][0] == secteur){
if (zonesSalles[i][1] == zone){
salles.push([zonesSalles[i][2]]);
}
}
}
salles.push(["Non définie"]);
salles.forEach(function(x){
if(tSalles.indexOf(x[0]) === -1){
tSalles.push(x[0])
}
});
var selectSalles = [];
for (let i = 0; i < tSalles.length; i ++){
if(tSalles[i] === "Choisissez..."){
selectSalles.push('<option disabled selected>Choisissez...</option>');
}
else{
selectSalles.push('<option>' + tSalles[i] + '</option>');
}
}
return selectSalles.join('');
}
function getMachines(salle){
const classeur = SpreadsheetApp.getActiveSpreadsheet();
const feuille = classeur.getSheetByName('BDD');
var sallesMachines = feuille.getRange('C2:E').getValues().filter(d =>d[0] !== '');
var machines = [["Choisissez..."]], tMachines = [];
for (let i = 0; i < sallesMachines.length; i ++){
if (sallesMachines[i][0] == salle){
machines.push([sallesMachines[i][2]]);
}
}
machines.push(["Non définie"]);
machines.forEach(function(x){
if(tMachines.indexOf(x[0]) === -1){
tMachines.push(x[0])
}
});
var selectMachines = [];
for (let i = 0; i < tMachines.length; i ++){
if(tMachines[i] === "Choisissez..."){
selectMachines.push('<option disabled selected>Choisissez...</option>');
}
else{
selectMachines.push('<option>' + tMachines[i] + '</option>');
}
}
return selectMachines.join('');
}
And this is my "edit request"'s page :
<form id= "divFormulaire">
<!-- TITRE -->
<h1 class="titre">FORMULAIRE DE DEMANDE D'INTERVENTION</h1>
<h2 class="sousTitre">1. Localisation :</h2>
<div class="form-row divHtml">
<div class="form-group col-md-10">
<label for="idDemande" class="intitulesChamps">ID de la demande : </label>
<input type="text" id="idDemande" class="form-control">
</div>
</div>
<div class="form-row divHtml">
<div class="form-group col-md-5">
<label for="secteur" class="intitulesChamps">Secteur : <span style="color: #e7343f">*</span></label>
<select type="text" id="secteur" class="form-control" onchange="getZonesJS(secteur);showResponsable()">
<option disabled selected>Choisissez...</option>
<?!=getSecteurs()?>
</select>
</div>
<div class="form-group col-md-5">
<label for="zone" class="intitulesChamps">Zone : <span style="color: #e7343f">*</span></label>
<select type="text" id="zone" class="form-control" onchange="getSallesJS(zone)">
</select>
</div>
</div>
<div class="form-row divHtml">
<div class="form-group col-md-5">
<label for="salle" class="intitulesChamps">Salle : <span style="color: #e7343f">*</span></label>
<select type="text" id="salle" class="form-control" onchange="getMachinesJS(salle)">
</select>
</div>
<div class="form-group col-md-5">
<label for="machine" class="intitulesChamps">Machine : <span style="color: #e7343f">*</span></label>
<select type="text" id="machine" class="form-control">
</select>
</div>
</div>
<h2 class="sousTitre">2. Description de la demande :</h2>
<div class="form-row divHtml">
<div class="form-group col-md-8">
<label for="description" class="intitulesChamps">Veuillez décrire votre demande en quelques mots :
<span style="color: #e7343f">*</span>
</label>
<label for="description"><b></b></label>
<textarea type="text" class="form-control" id="description" rows="5" cols="100" placeholder="(nom du demandeur si différent du responsable de secteur, que s'est-il passé, à quel moment, à quelle fréquence,...)" required></textarea>
</div>
</div>
<div class="form-row divHtml">
<div class="form-group col-md-4">
<label for="equipementStrategique"><b>Équipement stratégique : <span style="color: #e7343f">*</span></b></label>
<select type="text" id="equipementStrategique" class="form-control">
<option disabled selected>Choisissez...</option>
<?!=getEquipement()?>
</select>
</div>
<div class="form-group col-md-4">
<label for="interventionProd"><b>Intervention possible en production :
<span style="color: #e7343f">*</span></b>
</label>
<select type="text" id="interventionProd" class="form-control">
<option disabled selected>Choisissez...</option>
<?!=getIntervention()?>
</select>
</div>
</div>
<div class="form-row divHtml">
<div class="form-group col-md-4">
<label for="disponibiliteZone"><b>Disponibilité de la zone : <span style="color: #e7343f">*</span></b></label>
<select type="text" id="disponibiliteZone" class="form-control">
<option disabled selected>Choisissez...</option>
<?!=getDisponibilite()?>
</select>
</div>
<div class="form-group col-md-4">
<label for="delai"><b>Délai : <span style="color: #e7343f">*</span></b></label>
<select type="text" id="delai" class="form-control" onchange="controleDelai()">
<option disabled selected>Choisissez...</option>
<?!=getDelai()?>
</select>
</div>
</div>
<div class="form-row divHtml">
<div class="form-group col-md-8" id="divDemandeUrgente">
<label for="dateDemandeUrgente">
<b>Sélectionnez la date correspondante : <span style="color: #e7343f">*</span></b>
</label>
<input type="date" id="dateDemandeUrgente" class="form-control">
</div>
</div>
<div class="form-row divHtml">
<div class="form-group col-12" id="divSubmit">
<input type="button" id = "btnSubmit" value="ENVOYER" onclick="submitForm()">
</div>
</div>
</form>
</body>
<script>
document.addEventListener("DOMContentLoaded",changeValuesOfEditForm);
</script>
Could you please help me to solve this problem? If you need, i can give you access of my Sheets if you want. Thank you for advance.

I managed to solve the problem. I don't think this is the most optimal way to do it, but here's what I did.
In the modifyValues(id) function, I called the other functions that I used to populate my cascading drop-down menus. I had to apply an increasingly large sleep in each of them so that they could allow time for the functions to execute and thus for the dropdowns to load the necessary data.
Here is part of JS code::
google.script.run.withSuccessHandler(secteur => {
document.getElementById("secteur").value = secteur;
getZonesJS(secteur);
}).getSecteurEdit(id);
sleep(3000).then(() =>{
google.script.run.withSuccessHandler(zone => {
document.getElementById("zone").value = zone;
getSallesJS(zone);
}).getZoneEdit(id);
});
sleep(6000).then(() =>{
google.script.run.withSuccessHandler(salle => {
document.getElementById("salle").value = salle;
getMachinesJS(salle);
}).getSalleEdit(id);
});
sleep(11000).then(() =>{
google.script.run.withSuccessHandler(machine => {
document.getElementById("machine").value = machine;
}).getMachineEdit(id);
});

Related

Incorrect result of loop

I study Java Script and faced the problem that during looping the result of last cycle is inserted not at the last but at first.
My Code:
//Determine annuity
const annuity = document.querySelector('#annuityType');
let payment = document.querySelector('#cashFlowType');
function showAnnuity() {
payment.innerHTML = ``;
payment = document.querySelector('#cashFlowType');
payment.innerHTML = `<label for="annuity">Сума ануїтету </label><input id="annuity" name="annuity" type="text"><br><br>`;
}
annuity.onclick = showAnnuity;
//Determine different cash flows
const different = document.querySelector('#differentType');
function showDifferentType() {
payment.innerHTML = ``;
payment = document.querySelector('#cashFlowPeriods');
let newPayment;
for (let i = 1; i <= document.querySelector('#period').value; i++) {
if (i == 1) {
newPayment = document.querySelector('#cashFlowOne');
newPayment.innerHTML = `<label for="diffCashFlow">Income for period <span id="periodDiff">1 </span></label><input id="diffCashFlow" name="differentCashFlow" type="text"><br><br>`;
} else {
let np = newPayment.cloneNode(true);
np.id = i;
document.querySelector('#periodDiff').innerHTML = i + " ";
payment.append(np);
}
}
}
different.onclick = showDifferentType;
<div>
<label for="period">Строк проекту (у роках)</label>
<input id="period" name="period" type="text">
</div>
<div>
<p>What kind of payment?</p>
<label for="annuityType">Annuity</label>
<input id="annuityType" name="cashFlowType" type="radio">
<label for="differentType">Different payments</label>
<input id="differentType" name="cashFlowType" type="radio">
</div><br>
<div id="cashFlowType"></div>
<div id="cashFlowPeriods">
<div id="cashFlowOne"><span id="periodDiff"></span></div>
</div>
For example, when I insert 5 into input "period", the sequence of results of loop is next:
Income for period 5
Income for period 1
Income for period 2
Income for period 3
Income for period 4
I tried to researched the reason but didn't find it. I will be grateful for any help.
You need to assign the innerHTML of the cloned node, not the original node after you cloned it.
Since IDs shouldn't be repeated, change id="periodDiff" to class="periodDiff".
//Determine annuity
const annuity = document.querySelector('#annuityType');
let payment = document.querySelector('#cashFlowType');
function showAnnuity() {
payment.innerHTML = ``;
payment = document.querySelector('#cashFlowType');
payment.innerHTML = `<label for="annuity">Сума ануїтету </label><input id="annuity" name="annuity" type="text"><br><br>`;
}
annuity.onclick = showAnnuity;
//Determine different cash flows
const different = document.querySelector('#differentType');
function showDifferentType() {
payment.innerHTML = ``;
payment = document.querySelector('#cashFlowPeriods');
let newPayment;
for (let i = 1; i <= document.querySelector('#period').value; i++) {
if (i == 1) {
newPayment = document.querySelector('#cashFlowOne');
newPayment.innerHTML = `<label for="diffCashFlow">Income for period <span class="periodDiff">1 </span></label><input class="diffCashFlow" name="differentCashFlow" type="text"><br><br>`;
} else {
let np = newPayment.cloneNode(true);
np.id = i;
np.querySelector(".periodDiff").innerHTML = i + " ";
payment.append(np);
}
}
}
different.onclick = showDifferentType;
<div>
<label for="period">Строк проекту (у роках)</label>
<input id="period" name="period" type="text">
</div>
<div>
<p>What kind of payment?</p>
<label for="annuityType">Annuity</label>
<input id="annuityType" name="cashFlowType" type="radio">
<label for="differentType">Different payments</label>
<input id="differentType" name="cashFlowType" type="radio">
</div><br>
<div id="cashFlowType"></div>
<div id="cashFlowPeriods">
<div id="cashFlowOne"><span id="periodDiff"></span></div>
</div>
you need to create elements using document.createElement instead of relying on building it using .innerHTML which can be risky if misused.
//Determine annuity
const annuity = document.querySelector('#annuityType');
let payment = document.querySelector('#cashFlowType');
function showAnnuity(){
payment.innerHTML = ``;
payment = document.querySelector('#cashFlowType');
payment.innerHTML = `<label for="annuity">Сума ануїтету </label><input id="annuity" name="annuity" type="text"><br><br>`;
}
annuity.onclick = showAnnuity;
//Determine different cash flows
const different = document.querySelector('#differentType');
function showDifferentType(){
payment.innerHTML = ``;
payment = document.querySelector('#cashFlowPeriods');
let newPayment;
let html = '';
for(let i = 1; i <= document.querySelector('#period').value; i++){
let label = document.createElement('label');
let input = document.createElement('input');
let br = document.createElement('br');
input.id = `periodDiff${i}`;
label.htmlFor = input.id;
label.innerText = `Income for period ${i} `;
payment.append(label);
payment.append(input);
payment.append(br);
}
}
different.onclick = showDifferentType;
<div>
<label for="period">Строк проекту (у роках)</label>
<input id="period" name="period" type="text">
</div>
<div>
<p>What kind of payment?</p>
<label for="annuityType">Annuity</label>
<input id="annuityType" name="cashFlowType" type="radio">
<label for="differentType">Different payments</label>
<input id="differentType" name="cashFlowType" type="radio">
</div><br>
<div id="cashFlowType"></div>
<div id="cashFlowPeriods"><div id="cashFlowOne"> <span id="periodDiff"></span></div></div>
<div>

need to append user data to array

my original question got answered but I realize that every time I try to push user data in the arrays it wouldn't allow me to do is there any another to append data to arrays or is the push method the only way. or should i create a new array................................................................
"use strict"
const names = ["Ben", "Joel", "Judy", "Anne"];
const scores = [88, 98, 77, 88];
const $ = selector => document.querySelector(selector);
const addScore = () => {
// get user entries
const name = $("#name").value;
const score = parseInt($("#score").value);
let isValid = true;
// check entries for validity
if (name == "") {
$("#name").nextElementSibling.textContent = "This field is required.";
isValid = false;
} else {
$("#name").nextElementSibling.textContent = "";
}
if (isNaN(score) || score < 0 || score > 100) {
$("#score").nextElementSibling.textContent = "You must enter a valid score.";
isValid = false;
} else {
$("#score").nextElementSibling.textContent = "";
}
if (isValid) {
names.push("#name");
scores.push("#score");
names[names.length] = name;
scores[scores.length] = score;
$("#name").value = "";
$("#score").value = "";
}
$("#name").focus();
};
// display scores
const displayScores = () => {
for (let i = 0; i < names.length; i++) {
document.getElementById("scores_display").textContent += names[i] + " = " +
scores[i] +
"\n";
}
};
document.addEventListener("DOMContentLoaded", () => {
$("#add").addEventListener("click", addScore);
$("#display_scores").addEventListener("click", displayScores())
$("#name").focus();
});
<main>
<h1>Use a Test Score array</h1>
<div>
<label for="name">Name:</label>
<input type="text" id="name">
<span></span>
</div>
<div>
<label for="score">Score:</label>
<input type="text" id="score">
<span></span>
</div>
<div>
<label> </label>
<input type="button" id="add" value="Add to Array">
<input type="button" id="display_scores" value="Display Scores">
</div>
<div>
<textarea id="scores_display"></textarea>
</div>
</main>
All my previous notes were incorrect. Your adhoc $ const threw me off! My apologies.
The issue was you weren't calling displayScores() after updating the array. Plus, I added a line to that function to clear the existing text before looping through your data.
"use strict"
const names = ["Ben", "Joel", "Judy", "Anne"];
const scores = [88, 98, 77, 88];
const $ = selector => document.querySelector(selector);
const addScore = () => {
// get user entries
const name = $("#name").value;
const score = parseInt($("#score").value);
let isValid = true;
// check entries for validity
if (name == "") {
$("#name").nextElementSibling.textContent = "This field is required.";
isValid = false;
} else {
$("#name").nextElementSibling.textContent = "";
}
if (isNaN(score) || score < 0 || score > 100) {
$("#score").nextElementSibling.textContent = "You must enter a valid score.";
isValid = false;
} else {
$("#score").nextElementSibling.textContent = "";
}
if (isValid) {
names.push("#name");
scores.push("#score");
names[names.length] = name;
scores[scores.length] = score;
$("#name").value = "";
$("#score").value = "";
// add to the textarea
displayScores()
}
$("#name").focus();
};
// display scores
const displayScores = () => {
document.getElementById("scores_display").textContent = "";
for (let i = 0; i < names.length; i++) {
document.getElementById("scores_display").textContent += names[i] + " = " +
scores[i] +
"\n";
}
};
document.addEventListener("DOMContentLoaded", () => {
$("#add").addEventListener("click", addScore);
$("#display_scores").addEventListener("click", displayScores())
$("#name").focus();
});
<main>
<h1>Use a Test Score array</h1>
<div>
<label for="name">Name:</label>
<input type="text" id="name">
<span></span>
</div>
<div>
<label for="score">Score:</label>
<input type="text" id="score">
<span></span>
</div>
<div>
<label> </label>
<input type="button" id="add" value="Add to Array">
<input type="button" id="display_scores" value="Display Scores">
</div>
<div>
<textarea rows="6" id="scores_display"></textarea>
</div>
</main>

Keep html that is generated with javascript after laravel POST with old data

There are 2 fields that belong together price and size. Some products have more then 1 size, so the html offers a button to generate more fields. However if some validation fails the fields are gone and not populated anymore.
Here are the non generated html fields
<div class="col-md-6">
<label for="price" class="form-label">Prijs* </label>
<input type="text"
name="priceAndSize[price][0]"
class="form-control #if($errors->has('priceAndSize.price.*')) border-danger #endif"
id="price"
value="{{ old('priceAndSize.price[0]') }}">
</div>
<div class="col-md-6">
<label for="stock" class="form-label">Inhoud in ml</label>
<input type="text"
name="priceAndSize[size][0]"
class="form-control"
id="size"
value="{{ old('priceAndSize.size[0]') }}">
</div>
With a button to generate more fields
<input type="button" class="btn btn-info mt-3 text-white" onclick="addInput()"
value="Meerdere prijzen & inhoud"/>
the javascript to generate the fields:
counter = 1;
function addInput() {
// Input
const newInputPrice = document.createElement('input');
newInputPrice.id = 'price' + counter;
newInputPrice.name = 'priceAndSize[price][' + counter + ']';
newInputPrice.type = 'text';
newInputPrice.className = 'form-control';
const newInputSize = document.createElement('input');
newInputSize.id = 'size' + counter;
newInputSize.name = 'priceAndSize[size][' + counter + ']';
newInputSize.type = 'text';
newInputSize.className = 'form-control';
// Label
const labelPrice = document.createElement('label');
labelPrice.htmlFor = 'price' + counter;
labelPrice.innerHTML = 'Prijs* ';
labelPrice.className = 'form-label';
const labelSize = document.createElement('label');
labelSize.htmlFor = 'size' + counter;
labelSize.innerHTML = 'Inhoud* ';
labelSize.className = 'form-label';
// New boostrap div
const newDivPrice = document.createElement('div');
newDivPrice.className = 'col-md-6';
const newDivSize = document.createElement('div');
newDivSize.className = 'col-md-6';
// Add label and input to div
newDivPrice.appendChild(labelPrice);
newDivPrice.appendChild(newInputPrice);
newDivSize.appendChild(labelSize);
newDivSize.appendChild(newInputSize);
const currentDiv = document.getElementById("test");
currentDiv.appendChild(newDivPrice);
currentDiv.appendChild(newDivSize);
counter++;
}
You can try this in your blade.
$priceAndSize = Request::old('priceAndSize');
#if(count($priceAndSize[price]) > 0)
for (var i = 1; i <= {{count($priceAndSize[price])}}; i++) {
addInput();
}
#elseif(count($priceAndSize[size]) > 0)
for (var i = 1; i <= {{count($priceAndSize[size])}}; i++) {
addInput();
}
#endif

Firestore document pages

I'm trying to make an HTML table that lists the names of people in my firestore database then when clicked on their row comes up with a page where it contains some information and then gives me the option to upload some new information about them.
It works for until I upload the set of data than when I click on the other pages it doesn't load any data. I'm sorry in advance, its a lot of code to look through because i don't know where the problem is.
<div class="URP_div" id="URP" style="display: none;">
<h1 id="StudentPage"></h1>
<div class="SPROW">
<labe>Name:</label>
<label id="SName"></label>
</div>
<div class="SPROW">
<label for="">IRL:</label>
<label id="SId"></label>
</div>
<div class="SPROW">
<label for="">Session Date:</label>
<label for="" id="SSd"></label>
</div>
<div class="SPROW">
<label for="">Exam Level:</label>
<label for="" id="SEl"></label>
</div>
<div class="SPROW">
<label for="">Exam Genre:</label>
<label for="" id="SEg"></label>
</div>
<div class="SPROW">
<label for="">Teacher ID:</label>
<label for="" id="STId"></label>
</div>
<div id="AGR">
<div class="ExaminerArea-Results1">
<label>Accredited Grade Results</label>
<input type="number" placeholder="Technique: (15)" id="Res1" class="Results-input">
<input type="number" placeholder="Control: (15)" id="Res2" class="Results-input">
<input type="number" placeholder="Stanima & Agility: (15)" id="Res3" class="Results-input">
<input type="number" placeholder="Musicality: (15)" id="Res4" class="Results-input">
<input type="number" placeholder="Interpretation: (10)" id="Res5" class="Results-input">
</div>
<div class="ExaminerArea-Results2">
<input type="number" placeholder="Knowledge: (15)" id="Res6" class="Results-input">
<input type="number" placeholder="Performance Skills: (5)" id="Res7" class="Results-input">
<input type="number" placeholder="Personal Discipline: (10)" id="Res8" class="Results-input">
</div>
</div>
<div id="NAGR">
<div class="FSPO">
<label>Foundation/Street/Performance Only</label>
<select name="FSPO" id="RPMD">
<option value="Not Awarded" selected="">Not Awarded</option>
<option value="Pass">Pass</option>
<option value="Merit">Merit</option>
<option value="Distingtion">Distinction</option>
</select>
</div>
</div>
<div class="SPROW">
<textarea name="ResultsComment" id="RC" cols="30" rows="10" placeholder="Exam Comments...."
maxlength="200"></textarea>
</div>
<button onclick="SumbitResult()">Upload</button>
<button onclick="BURP()">Back</button>
<button onclick="logout()">Logout</button>
</div>
function BURP() {
document.getElementById('URP').style.display = "none";
document.getElementById('exam').style.display = "block";
document.getElementById('SName').innerHTML = "";
document.getElementById('SId').innerHTML = "";
document.getElementById('SSd').innerHTML = "";
document.getElementById('SEl').innerHTML = "";
document.getElementById('SEg').innerHTML = "";
document.getElementById('STId').innerHTML = "";
document.getElementById('StudentPage').innerHTML = "";
var table = document.getElementById('StduentTable')
for (var i = table.rows.length - 1; i > 0; i--) {
table.deleteRow(i);
}
var db = firebase.firestore();
console.log(CRSD);
db.collection("Students").where('SessionDate', '==', CRSD).where('TeacherID', '==', CRTID).onSnapshot(function (querySnapshot) {
querySnapshot.forEach(function (doc) {
var data = doc.data();
var content = '';
content += '<tr>';
content += '<td id="name">' + data.Student + '</td>';
content += '<td id="id">' + data.StudentID + '</td>';
content += '<td id="eg">' + data.ExamGenre + '</td>';
content += '<td id="el">' + data.ExamLevel + '</td>';
content += '<td>' + '<button class="btn" onclick="URP()">Upload Results</button>' + '</td>';
$('#StduentTable').append(content);
})
});
}
var cel1;
var cel2;
var cel3;
var cel4;
$('#StduentTable').on('click', '.btn', function () {
var currow = $(this).closest('tr');
cel1 = currow.find('td:eq(0)').text();
cel2 = currow.find('td:eq(1)').text();
cel3 = currow.find('td:eq(2)').text();
cel4 = currow.find('td:eq(3)').text();
console.log(cel1)
console.log(cel2)
console.log(cel3)
console.log(cel4)
var table = document.getElementById("StduentTable");
var CRSD = document.getElementById('RSD').value;
var CRTID = document.getElementById('RTID').value;
document.getElementById('URP').style.display = "block";
document.getElementById('exam').style.display = "none";
var db = firebase.firestore();
db.collection("Students").where('SessionDate', '==', CRSD).where('TeacherID', '==', CRTID).where('Student', '==', cel1).where('StudentID', '==', cel2).where('ExamLevel', '==', cel4).where('ExamGenre', '==', cel3).onSnapshot(function (querySnapshot) {
querySnapshot.forEach(function (doc) {
console.log('test');
var data = doc.data();
var text = data.Student + "'s Page.";
DS = data.Student;
DSID = data.StudentID;
DSSD = data.SessionDate;
DSEL = data.ExamLevel;
DSEG = data.ExamGenre;
DSTID = data.TeacherID;
document.getElementById('StudentPage').innerHTML = text;
document.getElementById('SName').innerHTML = DS;
document.getElementById('SId').innerHTML = DSID;
document.getElementById('SSd').innerHTML = DSSD;
document.getElementById('SEl').innerHTML = DSEL;
document.getElementById('SEg').innerHTML = DSEG;
document.getElementById('STId').innerHTML = DSTID;
})
});
})
<script>
function SumbitResult() {
var CRSD = document.getElementById('RSD').value;
var CRTID = document.getElementById('RTID').value;
var dataIn = false
var db = firebase.firestore();
var r1 = document.getElementById('Res1').value;
var r2 = document.getElementById('Res2').value;
var r3 = document.getElementById('Res3').value;
var r4 = document.getElementById('Res4').value;
var r5 = document.getElementById('Res5').value;
var r6 = document.getElementById('Res6').value;
var r7 = document.getElementById('Res7').value;
var r8 = document.getElementById('Res8').value;
var ExamComment = document.getElementById('RC').value;
var NAW = document.getElementById('RPMD').value;
var totalscore =
document.getElementById('Res1').valueAsNumber +
document.getElementById('Res2').valueAsNumber +
document.getElementById('Res3').valueAsNumber +
document.getElementById('Res4').valueAsNumber +
document.getElementById('Res5').valueAsNumber +
document.getElementById('Res6').valueAsNumber +
document.getElementById('Res7').valueAsNumber +
document.getElementById('Res8').valueAsNumber;
var tot2 = totalscore;
if (NAW !== "Not Awarded") {
r1 = 0;
r2 = 0;
r3 = 0;
r4 = 0;
r5 = 0;
r6 = 0;
r7 = 0;
r8 = 0;
r9 = 0;
r10 = 0;
tot2 = 0;
}
var OverallResult;
if (tot2 > 89) {
OverallResult = "Distingtion with Honours"
}
if (tot2 > 76 && tot2 < 88) {
OverallResult = "Distingtion"
}
if (tot2 > 58 && tot2 < 75) {
OverallResult = "Merit"
}
if (tot2 > 43 && tot2 < 57) {
OverallResult = "Pass"
}
if (tot2 <= 42) {
OverallResult = "Not Awared"
}
db.collection("Students").where("SessionDate", "==", CRSD)
.where('SessionDate', '==', CRSD).where('TeacherID', '==', CRTID).where('Student', '==', cel1).where('StudentID', '==', cel2).where('ExamLevel', '==', cel4).where('ExamGenre', '==', cel3)
.onSnapshot(function (querySnapshot) {
querySnapshot.forEach(function (doc) {
db.collection("Students").doc(doc.id).update({
"Results.Results1": r1,
"Results.Results2": r2,
"Results.Results3": r3,
"Results.Results4": r4,
"Results.Results5": r5,
"Results.Results6": r6,
"Results.Results7": r7,
"Results.Results8": r8,
"Results.TotalScore": tot2,
"Results.Exam_Comments": ExamComment,
"Results.Non_Accredited_Exam": NAW,
"Results.Examiner_ID": DBID,
"Results.Overall_Results": OverallResult
})
dataIn = true;
})
});
if (dataIn = true) {
document.getElementById('REG').value = "";
document.getElementById('REL').value = "";
document.getElementById('RSD').value = "";
document.getElementById('RCID').value = "";
document.getElementById('RTID').value = "";
document.getElementById('RC').value = "";
document.getElementById('Res1').value = "";
document.getElementById('Res2').value = "";
document.getElementById('Res3').value = "";
document.getElementById('Res4').value = "";
document.getElementById('Res5').value = "";
document.getElementById('Res6').value = "";
document.getElementById('Res7').value = "";
document.getElementById('Res8').value = "";
}
}
</script>

Save array of data

I have use jquery in adding new input type as long as the user want it.
#using (Html.BeginForm("addBatch_CARF", "CARF", FormMethod.Post, new { #name = "register" }))
{
#Html.ValidationSummary(true)
<div id="formAlert" class="alert alert-danger">
<a class="close">×</a>
<strong>Warning!</strong> Make sure all fields are filled and try again.
</div>
var catName = "";
var displayCan = "";
var candidates = "";
for (int i = 0; i < Model.Count; i++)
{
if (catName != Model[i].request_category)
{
<li class="list-group-item list-group-item-success">
#Html.DisplayFor(modelItem => Model[i].request_category)
<span class="pull-right" style="margin-right:60px;">Special Instructions</span>
</li>
catName = Model[i].request_category;
displayCan = catName;
}
if (displayCan == Model[i].request_category)
{
candidates = Model[i].request_name;
<div class="checkbox_request">
#Html.CheckBoxFor(model => model[i].isSelected, new { #class = "is_selected" })
#Html.DisplayFor(model => model[i].request_name)
#if(Model[i].request_name == "Folder Access")
{
<span class="label label-danger">Pls specify all the drive path. Note: For accessing of drives outside PETC please proceed to Online CARF</span>
}
<span class="pull-right">
#Html.EditorFor(model => model[i].special_instruction)
</span>
#Html.HiddenFor(model => model[i].request_type_id)
#Html.HiddenFor(model => model[i].system_roles_id)
</div>
}
}
<li class="list-group-item list-group-item-success">
Access to:
</li>
<div class="input_fields_wrap">
<button class="add_field_button btn btn-primary">Add More Fields</button>
<div>
<input type="text" name="fname[]" placeholder="First Name">
<input type="text" name="lname[]" placeholder="Last Name">
<input type="text" name="email_add[]" placeholder="Email Address">
<input type="text" name="user_id[]" placeholder="User ID">
</div>
</div>
<p class="request_btn">
<button type="submit" class="btn btn-primary" id="addbtn">Save</button>
</p>
}
Javascript
<script type="text/javascript">
$(document).ready(function () {
var max_fields = 10; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //Add button ID
var x = 1; //initlal text box count
$(add_button).click(function (e) { //on add input button click
e.preventDefault();
if (x < max_fields) { //max input box allowed
x++; //text box increment
$(wrapper).append('<div><input type="text" name="fname[]" placeholder="First Name"/> <input type="text" name="lname[]" placeholder="Last Name"/> <input type="text" name="email_add[]" placeholder="Email Add"/> <input type="text" name="user_id[]" placeholder="User ID"/>Remove</div>'); //add input box
}
});
$(wrapper).on("click", ".remove_field", function (e) { //user click on remove text
e.preventDefault(); $(this).parent('div').remove(); x--;
})
</script>
How will I add this data to my database? I've tried this code in my controller but these following parameters have no values string[] fname= null, string[] lname= null, string[] email_add= null, string[] user_id = null.
[HttpPost]
public ActionResult addBatch_CARF(List<Request_Type> list = null, string[] fname= null, string[] lname= null, string[] email_add= null, string[] user_id = null)
{
var data = db.Employees_All_vw.Where(x => x.NT_Name == #User.Identity.Name.Remove(0, 9).ToLower() && x.active_flag == true).FirstOrDefault();
//add data into CARF table
CARF carf = new CARF();
carf.requestor = data.Emp_Badge_No;
carf.carf_type = "BATCH CARF";
carf.created_by = #User.Identity.Name.Remove(0, 9).ToLower();
carf.created_date = System.DateTime.Now;
carf.active_flag = true;
db.CARves.Add(carf);
db.SaveChanges();
int id = carf.carf_id;
//add data into Request Access Table
foreach (var i in list)
{
int val = 1;
bool y = Convert.ToBoolean(val);
if (i.isSelected == y)
{
Request_Access ra = new Request_Access();
ra.request_access_id = 1;
ra.carf_id = id;
ra.request_type_id = i.request_type_id;
ra.special_instruction = i.special_instruction;
ra.ra_assignee = i.system_roles_id;
ra.dept_approval = null;
ra.dept_approval_date = null;
ra.dept_remarks = null;
ra.final_approval = null;
ra.final_approval_date = null;
ra.final_remarks = null;
ra.acknowledge_by = null;
ra.acknowledge_date = null;
ra.journal = null;
ra.closed_by = null;
ra.closed_date = null;
ra.verified_by = null;
ra.verified_date = null;
db.Request_Access.Add(ra);
}
db.SaveChanges();
}
//add all list of names to the Batch CARF table
for (var x = 1; x < fname.Count(); x++)
{
//foreach(var x in fname)
Batch_CARF batch = new Batch_CARF();
batch.carf_id = id;
batch.fname = fname[x];
batch.lname = lname[x];
batch.email_add = email_add[x];
batch.user_id = user_id[x];
batch.active_flag = true;
db.Batch_CARF.Add(batch);
}
db.SaveChanges();
//send email notification to the data owner or final approver by batch
TempData["MessageAlert"] = "Successfully created!";
return RedirectToAction("Batch_CARF");
}

Categories