I'm a beginner in Js and have a problem making a little program, I want to put the variables nome, document e Codigo, inside of the JSON array 'registros'
var registros = [];
var codigo = 1;
function salvar() {
var nome = document.getElementById("pNome").innerText;
var documento = document.getElementById("pDocumento").innerText;
var registro = [{
codigo: 0,
nome: "",
sexo: ""
}];
registro.push(codigo, nome, document);
}
You need to do a little adjustment in the salvar() function.
First, you can set each specific value of your "registro" var like this:
var registro = [{
codigo: codigo, //value = 1
nome: nome, //value = the innerText of document.getElementById("pNome")
sexo: ""
}];
Then, you use the push() function to insert "registro" into your "registros" array. Here is the full updated code:
var registros = [];
var codigo = 1;
function salvar() {
var nome = document.getElementById("pNome").innerText;
var documento = document.getElementById("pDocumento").innerText;
var registro = [{
codigo: codigo,
nome: nome,
sexo: ""
}];
registros.push(registro);
}
Array in JS comes in property/ value structure, and from your code you are assigning the values to a different variable registro instead of registros.
Moreover, the registros variable is never user.
To do this;
Create your array variable (registros)
Create a function (salvar)
Create an object that will hold your values, here nome in object will create a property name "nome" with the value being the value in nome which is document.get ...;
var obj = { "nome": document.getElementById("pNome").innerText.
Then push obj to array, registros
var registros = [];
var codigo = 1;
function salvar() {
var nome = document.getElementById("pNome").innerText;
var documento = document.getElementById("pDocumento").innerText;
var obj = { nome, documento, caodigo}
registros.push(obj);
}
Related
I have this program that as soon as it starts up, it asks you to enter the number of books that you want to register in the program and the number of authors that each book will have.
The program will ask you to register a name for each author, surname, age and nationality.
Once this is done, there is a button that shows all the books registered with their authors and the data of the books, and I have the problem that I am not able to show the data of the authors since only [object Object] appears.
Edit:
I have managed to print the element.autores by console.log, without the error obejct object appearing but I am not able to get it out through a document.write or something similar, here I leave a screenshot of how it should appear:
And if I try to put elements.autores.nombre to print only the name, it appears undefined both in the console.log and in the document.write
Here my code:
javascript:
var biblioteca = new Array();
function libro(titulo, autores, anyo, editorial) {
this.titulo = titulo;
this.autores = autores;
this.anyo = anyo;
this.editorial = editorial;
}
function autor(nombre, apellidos, edad, nacionalidad) {
this.nombre = nombre;
this.aepellidos = apellidos;
this.edad = edad;
this.nacionalidad = nacionalidad;
}
window.onload = function () {
document.getElementById("mostrar").onclick = Mostrar;
document.getElementById("insertar").onclick = insertarlibro;
document.getElementById("insertar").onclick = insertarautor;
}
function insertarlibro() {
var autores = new Array();
var titulo = prompt("Insertar el nombre del titulo del libro");
var anyo = parseInt(prompt("Año"));
var editorial = prompt("Inserta su editorial");
var numautores = parseInt(prompt("Cuantos autores vas a insertar"));
for (let i = 0; i < numautores; i++) {
let autor = insertarautor();
autores.push(autor);
}
var registrohecho = new libro(titulo, autores, anyo, editorial);
return registrohecho;
}
console.log(insertarlibro);
function insertarautor() {
var nombre = prompt("Insertar el nombre del autor").toUpperCase();
var apellidos = prompt("Insertar el apellidos del autor").toUpperCase();
var edad = parseInt(prompt("Edad"));
var nacionalidad = prompt("¿De que pais es el autor?");
var registrohecho = new autor(nombre, apellidos, edad, nacionalidad);
return registrohecho;
}
console.log(insertarautor);
var numlibros = parseInt(prompt("Cuantos libros vas a insertar"));
for (let i = 0; i < numlibros; i++) {
var insertalibro = insertarlibro();
biblioteca.push(insertalibro);
}
function Mostrar() {
biblioteca.forEach(element => {
console.log("Error" + JSON.stringify(element.autores));
var muestra = "Nombre del libro:" + element.titulo + " autores: " + element.autores + " Año en el que se publico: " + element.anyo + " Editorial: " + element.editorial;
document.write(muestra);
});
}
And the html part:
<div id="insertar">
<input type="button" value="Insertar">
</div>
<div id="mostrar">
<input type="button" value="Mostrar">
</div>
You are trying to get element.autores, which is an array. To get e.g. get the nombre, you wold have to acces it with element.autores[0].nombre.
So your code to output all books (with authors) would be something like this:
biblioteca.forEach(element => {
var muestra = "Nombre del libro:" + element.titulo + " autores: ";
element.autores.forEach(author => {
muestra += `nombre: ${author.nombre}, aepellidos: ${author.aepellidos}, edad: ${author.edad}, nacionalidad: ${author.nacionalidad} `;
})
muestra += "Año en el que se publico: " + element.anyo + " Editorial: " + element.editorial;
document.write(muestra);
});
Is it possible to use IndividualStudentsOptions object from Google Apps Script? I'm trying to create the object but returns this error
GoogleJsonResponseException: No se ha podido llamar a la API classroom.courses.courseWork.create; error: Invalid JSON payload received. Unknown name "individualStudentsOptions" at 'course_work': Proto field is not repeating, cannot start list.
It seems that is not possible from GAS.
function enviarclassdos(datos,alumnos){
// datos: object with needed variables for classroom publishing
// alumnos: individual students (array [students])
var stdid = []; //Array of IDs of individual students
//Getting the IDs of the individual students
var hojacuentas = SpreadsheetApp.openById("1oHlpSyRB913LWpj-UNTKattO").getSheetByName("CUENTAS");
var datacuentas = hojacuentas.getDataRange().getValues();
for(var al =0; al<alumnos.length; al++){
var alum = alumnos[al][0];
for (var dt=0; dt<datacuentas.length; dt++){
var alumdt = datacuentas[dt][0];
if (alumdt == alum){
var cuenta = datacuentas[dt][3];
stdid.push(cuenta);}}}
var curso = datos.curso;
var tipo = datos.tipo;
if (curso == "Primero A"){var id = "14085771****";}
if (curso == "Primero B"){var id = "14085996****";}
if (curso == "Segundo A"){var id = "14085996****";}
if (curso == "Segundo B"){var id = "14085996****";}
if (curso == "Cuarto AB"){var id = "14085996****";}
var titulo = datos.concepto;
var descripcion = datos.descripcion;
var fecha = datos.fecha;
var tema = datos.tipo
var ClassSource =
{
title: titulo,
description: descripcion,
state: "PUBLISHED",
workType: "ASSIGNMENT",
topicId: tema,
maxPoints: 100,
assigneeMode: "INDIVIDUAL_STUDENTS"
}
//This is the object that produces the error message
ClassSource.individualStudentsOptions = {studentIds:stdid};
var clss = Classroom.Courses.CourseWork;
var wrk = clss.create(ClassSource, id);
}
Instead of
ClassSource.individualStudentsOptions = [{studentIds:stdid}];
use
ClassSource.individualStudentsOptions = {studentIds:[stdid]};
Reference
https://developers.google.com/classroom/reference/rest/v1/IndividualStudentsOptions
I have a HTML Site with 4 inputRange slidern. If a user click on a button all the values from the ranges should be stored in a nested JSON Object. So far so good, but JS only saves the last one in that Array and not the others before.
But all Sliders have different values from 1 to 5, but JS saves only the 4 from the last slider. Here's my code:
//Speichert die aktuellen Angaben in einem Nested-JSON Objekt
function saveBewertung() {
var jsonObj = {};
var kriterien = [];
var bewertungen = {};
//Loop
$('input[type=range]').each(function() {
var id = $(this).attr("id");
var note = $(this).val();
bewertungen.id = id;
bewertungen.note = note;
kriterien.push(bewertungen);
jsonObj.Bewertungen = kriterien;
});
jsonObj.Kommentar = $('textarea#kommentar').val();
//TEST AUSGABE
alert(JSON.stringify(jsonObj));
}
Result:
You are pushing the same object to the array again and again. You need to initialize bewertungen every time in the each block.
Declare
var bewertungen = {};
inside the each block
$('input[type=range]').each(function() {
var bewertungen = {};
var id = $(this).attr("id");
var note = $(this).val();
bewertungen.id = id;
bewertungen.note = note;
kriterien.push(bewertungen);
});
jsonObj.Bewertungen = kriterien; //this line can be moved out
Another possibility next to the solution from #gurvinder372 is to shorten the function so you don't need to declare the variables bewertungen, id and note:
//Speichert die aktuellen Angaben in einem Nested-JSON Objekt
function saveBewertung() {
var jsonObj = {};
var kriterien = [];
//Loop
$('input[type=range]').each(function() {
// Anonymous object
kriterien.push({
id: $(this).attr("id"),
note: $(this).val()
});
});
jsonObj.Bewertungen = kriterien;
jsonObj.Kommentar = $('textarea#kommentar').val();
//TEST AUSGABE
alert(JSON.stringify(jsonObj));
}
Here is some description how this thing is working
var bewertungen = {}; // this line declare the object this object will hold values in each loop.
$('input[type=range]').each(function() {
var bewertungen = {};
var id = $(this).attr("id");
var note = $(this).val();
bewertungen.id = id; // this line add value to {bewertungen} object key
bewertungen.note = note; // this line add value to {bewertungen} object key
kriterien.push(bewertungen); // every itration will push value to [kriterien] array
});
jsonObj.Bewertungen = kriterien; // this is final array with all values
I intend to run my script on Google sheet
What I'm doing is to restore the values of the cells, and use an if statement to compare an identifier cell with another userid cell.
If they are different, I want to eliminate that entire row, if they are equal I want to leaving the entire row as it is.
I get the error:
You can not convert CjwKEAjwiYG9BRCkgK-G45S323oSJABnykKAhI-
My code:
function myFunction() {
function Lento() {
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var sheet = spreadsheet.getActiveSheet();
var rows = sheet.getDataRange();
var values = rows.getValues();
var numCols = rows.getNumColumns();
var numRows = rows.getNumRows();
for (var r=1; r<values.length; r++) {
var row = values[r],
identificador = row[0],
palabraclave = row[1],
ciudad = row[2],
fecha = row[4],
pais = row[5],
idusuario = row[6],
nombre = row[7],
email = row[8],
telefono = row[9],
mensaje = row[10],
urllanding = row[11],
fechausuario = row[12];
Logger.log(identificador);
Logger.log(palabraclave);
Logger.log(ciudad);
Logger.log(fecha);
Logger.log(pais);
}
if (row[0] !== row[6]) {
spreadsheet.deleteRow(row);
}
}
Lento();
}
I think your problem is with spreadsheet.deleteRow(row). First, you want to delete the row on this particular sheet, so it should be sheet.deleteRow(...). The other problem is that deleteRow expects an integer as an argument, but you've provided row, which is an array. To delete the row, you want to do
sheet.deleteRow(r+1);
because r is the integer linked to the position in the array, not row. See the documentation on deleteRow(rowPosition):
https://developers.google.com/apps-script/reference/spreadsheet/sheet#deleterowrowposition
Now I have the solution to what I do.
as well as it gives errors since the comprovación of the array is null therefore not work , the code would look like .
function myFunction() {
function Lento() {
var h1 = SpreadsheetApp.getActive().getSheetByName('Hoja 1');
var h2 = SpreadsheetApp.getActive().getSheetByName('Hoja 2');
var rowsh1 = h1.getDataRange();
var valuesh1 = rowsh1.getValues();
var numColsh1 = rowsh1.getNumColumns();
var numRowsh1 = rowsh1.getNumRows();
var rowsh2 = h2.getDataRange();
var valuesh2 = rowsh2.getValues();
var numColsh2 = rowsh2.getNumColumns();
var numRowsh2 = rowsh2.getNumRows();
var idusuario = [];
var identificador = [];
//recorremos fila a fila y cogemos los datos de la hoja1
for (var r = 1; r < valuesh2.length; r++) {
var rowh2 = valuesh2[r],
nombre = rowh2[1],
email = rowh2[2],
telefono = rowh2[3],
mensaje = rowh2[4],
urllanding = rowh2[5],
fechausuario = rowh2[6];
idusuario[r] = rowh2[0]; //Guardamos los gclid del usuario en un array
}
//recorremos fila a fila y cogemos los datos de la hoja2
for (var r = 1; r < valuesh1.length; r++) {
var rowh1 = valuesh1[r],
palabraclave = rowh1[1],
ciudad = rowh1[2],
fecha = rowh1[4],
pais = rowh1[5];
identificador[r] = rowh1[0]; //Guardamos los gclid en un array
}
for (var i = identificador.length - 1; i >= 0; i--) {
var encontrado = false;
for (var y = 1; y < idusuario.length; y++) {
if (identificador[i] == null || idusuario[y] == null) continue;
if (identificador[i] == idusuario[y]) {
encontrado = true;
break;
}
}
if (!encontrado) {
h1.deleteRow(i + 1);
}
}
}
Lento();
}
im using JSON to parse some data from MYSQL, but in order to bring all the information in just one call i´m tring to stored everything in JAVASCRIPT OBJECTS(works fine), the problem is i don`t know how can i use with JQUERY to fill in some divs and integrated the info of the objects with different functions. this is how i worked:
// SE DEFINE CADA OBJETO QUE RECIBE INFO DE CADA CAMPO DE BD
//PLATO
function PlatoBD(nombreplato , descripcion, caloriasTortilla, precio, ingredientes)
{
this.nombreplato = nombreplato;
this.descripcion = descripcion;
this.caloriasTortilla = caloriasTortilla;
this.precio = precio;
this.ingredientes = function(adiciones , NomPlato){
peticionBD(adiciones , NomPlato);
}
}
//ADICION
function AdicionBD(nombreAdicion , calXplato, tipoAdicion)
{
this.nombreAdicion = nombreAdicion;
this.calXplato = calXplato;
this.tipoAdicion = tipoAdicion;
}
//SE DEFINE LA FUNCION PARA LLAMAR CUALQUIER BASE DE DATOS
function peticionBD(peticionBDJSON,NomPlato){
$.post('php/consulta-actualizar-info.php',
{"peticionBD" :peticionBDJSON }
,
function(data) {
var infophpData = $.parseJSON(data);
if (peticionBDJSON == "menuElpaso") {
ingred = new Array();
for (var i = 0; i < infophpData.length; i++) {
window["plato_"+infophpData[i]["plato"].replace(' ','_')] = new PlatoBD(infophpData[i]["plato"] , infophpData[i]["descripcion"] , infophpData[i]["caloriasTortilla"] , infophpData[i]["precio"]);
window["plato_"+infophpData[i]["plato"].replace(' ','_')].ingredientes("adiciones",infophpData[i]["plato"].replace(' ',''))
};
};
if (peticionBDJSON == "adiciones") {
else if (NomPlato =="Burritoveggy")
{
for (var i = 0; i < infophpData.length; i++) {
window["adicionesPara"+NomPlato+"De"+infophpData[i]["adicion"].replace(" ","_")] = new AdicionBD(infophpData[i]["adicion"] , infophpData[i][NomPlato], infophpData[i]["tipoAdicion"]);
};
}
else if (NomPlato =="Quesadilla")
{
for (var i = 0; i < infophpData.length; i++) {
window["adicionesPara"+NomPlato+"De"+infophpData[i]["adicion"].replace(" ","_")] = new AdicionBD(infophpData[i]["adicion"] , infophpData[i][NomPlato], infophpData[i]["tipoAdicion"]);
};
}
...
};
}).error(
function(){
alert('Error al ejecutar la petición');
},
'json'
)
}
$(document).ready(function($){
peticionBD("menuElpaso","")
});
the response result is(http://wedesign-medellin.com/restaurante-elPaso/objeto-bd-domicilios.html):
PlatoBD {nombreplato: "Almuerzo", descripcion: "Sopa + elecciones + gaseosa", caloriasTortilla: "250", precio: "14.000", ingredientes: function}
Use jQuery.parseJSON(string_object)