i need help trying to show up specific data and this time i need to sort out a table by clicking on genders. here is my html
<center>
<h1>Russestyret 2018</h1>
<br>
<header>
<nav>
Hjem
Registrering
Arragementer
</nav>
</header>
<hr>
<img src="bilder/russestyret2.png" width="400px">
<h4>Arrangementer</h4>
<form id="regarrangement">
<label>Arrangør: <input id="inparrangør" type="text" required></label>
<label>Adresse: <input id="inpregadress"type="text"required></label>
<label>Postadresse:<input id="inppostadresse" type="text"required></label>
<label>Poststed: <input id="inppoststed" type="tex"required></label>
<label>Pris: <input id=inppris type="text"required></label>
<button type="submit">Send inn</button>
</form>
<h4>Registrer en russ ved å fylle ut skjema under. Alle felter må fylles ut.</h4>
<form id="registrering">
<label>Navn: <input id="inpnavn" placeholder="Raahim Khan" type="text" required></label>
<label>Adresse: <input id="inpadresse" type="text" placeholder="Adresse 12" required></label>
<label>Mobilnummer: <input id="inpmobilnummer" placeholder="12345678" required></label>
<label>Kjønn:
<select id="inpkjønn" required>
<option value="" selected disabled hidden>Velg kjønn</option>
<option>Mann</option>
<option>Kvinne</option>
<option>intetkjønn</option>
</select>
<label>Arrangement: <select id="inparrang"></select></label>
</label>
<button type="submit">Send inn</button>
</form>
<br>
<br>
buttons allowing me to see either all the registered russ or only menn, women or neuter, visAlleruss stands for show allruss, visIntetKjønn for show neuter and so on with men and women.:
<button class="vis" onclick="visAlleruss()">Vis alle</button>
<button class="vis" onclick="visMenn()">Vis Menn</button>
<button class="vis" onclick="visKvinner()">Vis Kvinner</button>
<button class="vis" onclick="visIntetkjønn()">Vis intetkjønn</button>
<table border="2px" width="500px;">
<tr><th>Navn</th><th>Adresse</th><th>Mobilnummer</th><th>Kjønn</th><th>Arrangør</th><th>Adresse</th><th>Postadresse</th><th>Poststed</th><th>Pris</th><th>Slett:</th></tr>
<tbody id="txttabell"></tbody>
</table>
<br>
<br>
<br>
<br>
function below is to register russ/arrangement and bring them into the innerHTML
//Register "arrangement":
function registrerearrangement(event){
event.preventDefault();
// Henter ut verdiene til input-feltene
var arrangør = inpArrangør.value;
var adresse = inpAdresse.value;
var postadresse = inpPostadresse.value;
var poststed = inpPoststed.value;
var pris = inpPris.value;
var russ = inpRuss.value;
inpArrangør.value = "";
inpAdresse.value = "";
inpPostadresse.value = "";
inpPoststed.value = "";
inpPris.value = "";
inpRuss.value = "";
arrangement.push({
"arrangør" : arrangør,
"adresse" : adresse,
"postadresse" : postadresse,
"poststed" : poststed,
"pris" : pris,
"russ" : russ
});
}
//bring data from firebase into txtTabell.innerHTML
function hentArrangement(snapshot){
var pk = snapshot.key;
var nyTime = snapshot.val();
var russRef = database.ref("russ/" + nyTime.russ);
russRef.on("value", function(snapshotruss) {
var pkk = snapshotruss.key;
var russObj = snapshotruss.val();
txtTabell.innerHTML += `
<tr id="${pk}">
<td><label class="russlabel" onclick="edit('${pk}')">${nyTime.arrangør}</label><input type="text" class="editItem" style="display:none"></td>
<td>${nyTime.adresse}</td>
<td>${nyTime.postadresse}</td>
<td>${nyTime.poststed}</td>
<td>${nyTime.pris}</td>
<td>${russObj.navn}</td>
<td>${russObj.russadresse}</td>
<td>${russObj.mobilnr}</td>
<td>${russObj.kjonn}</td>
<td><label class="delete" onclick="slett('${pk}','${pkk}')"><button>Slett</button></label></td>
</tr>`;
});
}
//bring russ:
function hentRuss(snapshot){
var russNoekkel = snapshot.key;
var russInfo = snapshot.val();
inpRuss.innerHTML += `<option value="${russNoekkel}">${russInfo.navn}</option>`;
};
//register "russ":
function registrerruss(event) {
event.preventDefault();
var navn = inpNavn.value;
var russadresse = inpRussadresse.value;
var mobilnr = inpMobil.value;
var kjonn = inpKjønn.value;
inpNavn.value = "";
inpRussadresse.value = "";
inpMobil.value = "";
inpKjønn.value = "";
russ.push({
"navn" : navn,
"russadresse" : russadresse,
"mobilnr" : mobilnr,
"kjonn" : kjonn
});
}
skjema.onsubmit = registrerearrangement;
skjema2.onsubmit = registrerruss;
function below are functions for the button, the reason i am doing .on("child_added", hentRuss) is because the russ objects are the objects including the gender btw kjonn stands for gender.
function visAlleruss(){
txtTabell.innerHTML = "";
russ
.on("child_added", hentRuss);
}
function visMenn(){
txtTabell.innerHTML = "";
russ
.orderByChild("kjonn")
.equalTo("Mann")
.on("child_added", hentRuss);
}
function visKvinner(){
txtTabell.innerHTML = "";
russ
.orderByChild("kjonn")
.equalTo("Kvinne")
.on("child_added", hentRuss);
}
function visIntetkjønn(){
txtTabell.innerHTML = "";
russ
.orderByChild("kjonn")
.equalTo("intetkjønn")
.on("child_added", hentRuss);
}
Related
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>
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);
I'm trying to do my first form validation with only Vanilla JS.
I have a form, that has two selects in which you have to select your department and depending on this it will allow you to select another location. I made a script for this.
Now, when I relate another script which is formValidation, it doesn't work and I guess I'm doing the form validation well. I'm starting doing it so it only has one validation but it isn't working.
What could be the problem? When i wrote the form validation in the script file, it override the function or the selects so it didn't work. I don't know how to else doing a form validation because I'm new to JS and I'm not allowed to use jquery or anything.
Thanks
Here is the code pen:
https://codepen.io/yomiram/pen/abNMaMy
HTML :
<section id="formSection">
<span class="textForm">Formulario</span>
<hr>
<form action="/" id="form" action="GET">
<div class="form-group">
<input type="text" placeholder="Nombre" id="name" class="input-control" required/>
<input type="text" placeholder="Apellido" id="lastName" class="input-control" />
</div>
<div class="form-group">
<input type="email" placeholder="E-mail" id="email" class="input-control" required/>
</div>
<div class="form-group">
<select class="input-control" style="flex: 6" id="dpto" required>
<option selected="selected" class="department">Departamento</option>
</select>
<select class="input-control" placeholder="Localidad" id="location" style="flex:6" required>
<option selected="selected" class="department">Localidad</option>
</select>
</div>
<div class="form-group">
<input type="number" id="ci" class="input-control" placeholder="C.I" style="flex:6" required/>
</div>
<div class="form-group">
<input type="checkbox" name="conditions" id="conditions" required>
<label for="conditions" id="conditions"> Acepto las bases y condiciones</label><br>
</div>
<div class="form-group">
<input type="submit" id="formButton" class="formButton" value="Enviar">
</div>
</form>
</section>
SCRIPT JS (SELECT FUNCTION):
// DISPLAYING DATA IN SELECT
var dptosLocs = {
"Artigas":["Artigas"," Bella Unión"],
"Canelones":["Canelones"," Santa Lucía"],
"Montevideo":["Montevideo"],
"Salto":["Salto"," Daymán"," Arapey"]
};
var sel = document.getElementById('dpto');
var fragment = document.createDocumentFragment();
Object.keys(dptosLocs).forEach(function(dptosLoc, index) {
var opt = document.createElement('option');
opt.innerHTML = dptosLoc;
opt.value = dptosLoc;
fragment.appendChild(opt);
});
sel.appendChild(fragment);
document.getElementById("dpto").onchange = function() {defineDpto()};
function defineDpto() {
var dpto = document.getElementById("dpto").value;
if (dpto == "Artigas" ) {
var sel = document.getElementById('location');
var fragment = document.createDocumentFragment();
Object.values(dptosLocs["Artigas"]).forEach(function(dptosLoc, index) {
var opt = document.createElement('option');
opt.innerHTML = dptosLoc;
opt.value = dptosLoc;
fragment.appendChild(opt)
sel.appendChild(fragment);
});
} else if (dpto == "Canelones") {
document.getElementById('location').options.length = 0;
var sel = document.getElementById('location');
var fragment = document.createDocumentFragment();
Object.values(dptosLocs["Canelones"]).forEach(function(dptosLoc, index) {
var opt = document.createElement('option');
opt.innerHTML = dptosLoc;
opt.value = dptosLoc;
fragment.appendChild(opt)
sel.appendChild(fragment);
});
} else if (dpto == "Montevideo") {
document.getElementById('location').options.length = 0;
var sel = document.getElementById('location');
var fragment = document.createDocumentFragment();
Object.values(dptosLocs["Montevideo"]).forEach(function(dptosLoc, index) {
var opt = document.createElement('option');
opt.innerHTML = dptosLoc;
opt.value = dptosLoc;
fragment.appendChild(opt)
sel.appendChild(fragment);
});
} else if (dpto == "Salto") {
document.getElementById('location').options.length = 0;
var sel = document.getElementById('location');
var fragment = document.createDocumentFragment();
Object.values(dptosLocs["Salto"]).forEach(function(dptosLoc, index) {
var opt = document.createElement('option');
opt.innerHTML = dptosLoc;
opt.value = dptosLoc;
fragment.appendChild(opt)
sel.appendChild(fragment);
});
}
}
FORM VALIDATION:
function validar (){
var name, lastName, email, dpto, location, ci, condictions, expresion;
name = document.getElementById('name').value;
lastName = document.getElementById('lastName').value;
email = document.getElementById('email').value;
dpto = document.getElementById('dpto').value;
location = document.getElementById('location').value;
ci = document.getElementById('ci').value;
conditions = document.getElementById('conditions').value;
if (name === ""){
alert("El campo nombre está vacío");
}
}
The problem with your script is that the validar() function is never called.
Please, remember, if you write a function and you never call it in your code, it will never be executed.
What you have to do is to add the call to your validar() function in the onsubmit event of the form.
<form action="/" id="form" action="GET" onsubmit="return validar();">
And your validar() function should return false if the validation is not verified for the form.
if (name === ""){
alert("El campo nombre está vacío");
return false;
}
return true;
You should take a look at how events are called in javascript when dealing with forms.
You're missing the call to the validar function
<form .... onsubmit="return validar()">
Also validar should return false if the validation fails and true if it passes
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)
My code does not function in external file <script src="action_input.js"></script>.
I put this code in <body></body> or <head></head> and it does not function.
My code functions in <body><script> code js</script></body>, but not like so.
My code is:
// identify form elements:
var search_code = document.getElementById('search_code');
var insert_code = document.getElementById('insert_code');
var result = document.getElementById('result');
var button = document.getElementById('button');
var audio = new Audio('sound.wav');
// respond to button click
button.onclick = function validate() {
// show verification result:
if(search_code.value == insert_code.value) {
result.textContent = 'cod gasit';
result.className = "ok";
audio.play(); //http://soundbible.com/tags-winning.html
} else {
result.textContent = 'codul nu este corect';
result.className = "not-ok";
}
// clear input when wrong:
if (search_code.value !== insert_code.value) {
insert_code.value = '';
}
return false;
};
//sterge textul cand se da click pe input
function clearField(input) {
input.value = "";
};
My input is:
<form>
<input type="text" name="search_code" onfocus="clearField(this, this.placeholder='');" onblur="this.placeholder='introdu codul'" id="search_code" placeholder="introdu codul" autocomplete="off" value=""/><br/>
<input type="" name="insert_code" onfocus="clearField(this, this.placeholder='');" onblur="this.placeholder='scaneaza codul'" id="insert_code" placeholder="scaneaza codul" autocomplete="off" value=""/><br/><br/>
<input type="submit" id="button" name="button" value="verifica COD" />
</form>
Use e.preventDefault(); to prevent default action of submit button or use type='button'
There is no element having id result
Try this:
var search_code = document.getElementById('search_code');
var insert_code = document.getElementById('insert_code');
var result = document.getElementById('result');
var button = document.getElementById('button');
var audio = new Audio('sound.wav');
// respond to button click
button.onclick = function validate(e) {
e.preventDefault();
// show verification result:
if (search_code.value == insert_code.value) {
result.textContent = 'cod gasit';
result.className = "ok";
audio.play(); //http://soundbible.com/tags-winning.html
} else {
result.textContent = 'codul nu este corect';
result.className = "not-ok";
}
// clear input when wrong:
if (search_code.value !== insert_code.value) {
insert_code.value = '';
}
return false;
};
//sterge textul cand se da click pe input
function clearField(input) {
input.value = "";
};
<form>
<input type="text" name="search_code" onfocus="clearField(this, this.placeholder='');" onblur="this.placeholder='introdu codul'" id="search_code" placeholder="introdu codul" autocomplete="off" value="" />
<br/>
<input type="" name="insert_code" onfocus="clearField(this, this.placeholder='');" onblur="this.placeholder='scaneaza codul'" id="insert_code" placeholder="scaneaza codul" autocomplete="off" value="" />
<br/>
<br/>
<div id="result"></div>
<input type="submit" id="button" name="button" value="verifica COD" />
</form>