I'm trying to show a graph using Google Charts.
I am able to create the chart but I'm having trouble passing an array of Arrays to the addRows method . A chart appears but without any lines charted.
If I manually write the chart's values, it works:
data.addRows([
['mai 19, 07:01', 1, 1, 1, 1]
]);
but if I try to pass the values using the array of Arrays precos_madeira, I can only see the chart, no lines...
At the end of mainFunction() you can clearly see precos_madeira is an array of Arrays.
For testing purposes, you can use
mai 19, 07:01 Mundo 73 Transferir 1 149 Troca Premium: Madeira vendido (233)
on the input box next to the Calcular custo dos PP's comprados button and then click the button
Here's the full code:
<!DOCTYPE html>
<html>
<head>
<script type = "text/javascript" src = "https://www.gstatic.com/charts /loader.js">
</script>
<script type = "text/javascript">
google.charts.load('current', {packages: ['corechart','line']});
</script>
</head>
<body>
<p>1.Insere o numero de pps que queres gastar</p>
<input type="text" id="pps_a_gastar" maxlenght="100" value="pp's a gastar">
<p>2.Insere o as unidades por hora geradas em 'Aumento da produção de recursos de 20%' (para encontrar carrega em 'Bosque') </p>
<input type="text" id="unidades_hora" maxlenght="100" value="unidades/hora">
<script>
function calcula_unidades_semana(){
var un_h=document.getElementById("unidades_hora").value;
var x7_x24=parseInt(un_h)*7*24;
document.getElementById("_x7_x24").innerHTML = x7_x24;
}
function calcula_unidades_mes(){
var un_h=document.getElementById("unidades_hora").value;
var x30_x24=parseInt(un_h)*30*24;
document.getElementById("_x30_x24").innerHTML = x30_x24;
}
</script>
<p>3.Ao fim de uma semana, com o aumento de 20%, produzes mais</p>
<p id="_x7_x24"></p><p> unidades</p>
<button onclick="calcula_unidades_semana()">Calcular unidades geradas numa semana</button>
<p>3.Ao fim de um mes, com o aumento de 20%, produzes mais</p>
<p id="_x30_x24"></p><p> unidades</p>
<button onclick="calcula_unidades_mes()">Calcular unidades geradas num mes</button>
<p>---------------------------------------------------------------</p>
<p>Copia e cola TODAS as linhas do teu historico de pontos</p>
<input type="text" id="myText" maxlenght="10000" value="Some text...">
<button onclick="mainFunction()">Calcular custo dos PP's comprados</button>
<p>Teste:</p>
<p id="teste"></p>
<p>Input:</p>
<p id="input"></p>
<p>Total pp's comprados:</p>
<p id="total_pps"></p>
<p>Total pp's usados:</p>
<p id="total_pps_usados"></p>
<p>Total gasto em madeira:</p>
<p style="color:brown;" id="total_madeira"></p>
<p >Total gasto em argila:</p>
<p style="color:orange;" id="total_argila"></p>
<p>Total gasto em ferro:</p>
<p style="color:darkgrey;" id="total_ferro"></p>
<p>Precos pp:</p>
<p id="pp"></p>
<div id = "container" style = "width: 550px; height: 400px; margin: 0 auto">
</div>
<script>
var lines = [];
var linesLength;
var text, i, bool;
var line="";
var line_counter=0;
var total_pps_comprados=0;
var total_pps_usados=0;
var total_gasto_em_madeira=0;
var total_gasto_em_argila=0;
var total_gasto_em_ferro=0;
var precos_madeira=[];
var madeira_cont=0;
function displayLines(){
linesLength = lines.length;
text = "<ul>";
for (i = 0; i < linesLength; i++) {
text += "<li>" + lines[i] + "</li>";
}
text += "</ul>";
document.getElementById("input").innerHTML = text;
}
function obterLinhas(){
var input = document.getElementById("myText").value;
for (i = 0; i < input.length; i++) {
bool=input.substr(i, 1).localeCompare(")");
if ( bool ){
line = line.concat(input.substr(i, 1));
}
else{
var pos_transf = line.indexOf("Transferir");
if (pos_transf != -1 ){
total_pps_comprados+=obter_pps_comprados();
}
var pos_ut = line.indexOf("Utilizados");
if (pos_ut != -1 ){
total_pps_usados+=obter_pps_usados();
}
lines[line_counter]=line;
line_counter+=1;
line="";
}
}
}
function obter_qtd_de_recurso_gasto(linha_sem_principio, prim_esp){
var qtd="";
if ( linha_sem_principio.search("Madeira") != -1 ){
//Obter qtd de madeira gasta a comprar os pps
qtd=linha_sem_principio.slice(linha_sem_principio.indexOf("(")+1, linha_sem_principio.length);
total_gasto_em_madeira += parseInt(qtd);
}
if ( linha_sem_principio.search("Argila") != -1 ){
//Obter qtd de argila gasta a comprar os pps
qtd=linha_sem_principio.slice(linha_sem_principio.indexOf("(")+1, linha_sem_principio.length);
total_gasto_em_argila += parseInt(qtd);
}
if ( linha_sem_principio.search("Ferro") != -1 ){
//Obter qtd de ferro gasto a comprar os pps
qtd=linha_sem_principio.slice(linha_sem_principio.indexOf("(")+1, linha_sem_principio.length);
total_gasto_em_ferro += parseInt(qtd);
}
return parseInt(qtd);
}
function obter_valor_da_data(data_str){
var mes_str;
var mes_num;
var dia_str;
var hora_str;
var min_str;
//Obter mes
mes_str = data_str.slice(0, data_str.indexOf(" "));
//Transformar mes(string) num numero
switch(mes_str){
case "jan":
mes_num=1;
break;
case "fev":
mes_num=2;
break;
case "mar":
mes_num=3;
break;
case "abr":
mes_num=4;
break;
case "mai":
mes_num=5;
break;
case "jun":
mes_num=6;
break;
case "jul":
mes_num=7;
break;
case "ago":
mes_num=8;
break;
case "set":
mes_num=9;
break;
case "out":
mes_num=10;
break;
case "nov":
mes_num=11;
break;
case "dez":
mes_num=12;
}
//Obter dia
dia_str=data_str.slice(data_str.indexOf(" "), data_str.indexOf(","));
//Obter hora
hora_str=data_str.slice(data_str.indexOf(",")+1, data_str.indexOf(":"));
//Obter min
min_str=data_str.slice(data_str.indexOf(":")+1, data_str.indexOf("M"));
return mes_num*12/(31*24*60)+parseInt(dia_str)*31/(24*60)+(parseInt(hora_str)+1)*24/60+(parseInt(min_str)+1)*60;
}
function obter_pps_comprados(){
var pos_transf = line.indexOf("Transferir");
var qtd;
var data;
var valor;
if (pos_transf != -1 ){
data = line.slice(0, line.indexOf("M"));
valor = obter_valor_da_data(data);
var line_sem_principio = line.slice(pos_transf+10);
var primeiro_espaco = line_sem_principio.lastIndexOf(" ");
qtd = obter_qtd_de_recurso_gasto(line_sem_principio, primeiro_espaco);
var pps_comprados = line_sem_principio.slice(0, line_sem_principio.length-primeiro_espaco+1);
precos_madeira[madeira_cont]=[data, parseInt(qtd)/parseInt(pps_comprados), 1, 1, 1];
madeira_cont+=1;
return parseInt(pps_comprados);
}
}
function obter_pps_usados(){
var pos_ut = line.indexOf("Utilizados");
if (pos_ut != -1 ){
var line_sem_principio = line.slice(pos_ut+10);
var primeiro_espaco = line_sem_principio.lastIndexOf(" ");
var pps_us = line_sem_principio.slice(0, line_sem_principio.length-primeiro_espaco+5); //nao deveria funcionar quando os novos pontos premium nao tem 3 digitos
return parseInt(pps_us);
}
}
function mainFunction() {
var text;
obterLinhas();
displayLines();
document.getElementById("total_pps").innerHTML = total_pps_comprados;
document.getElementById("total_pps_usados").innerHTML = total_pps_usados;
document.getElementById("total_madeira").innerHTML = total_gasto_em_madeira;
document.getElementById("total_argila").innerHTML = total_gasto_em_argila;
document.getElementById("total_ferro").innerHTML = total_gasto_em_ferro;
text = "<ul>";
for (i = 0; i < precos_madeira.length; i++) {
text += '<li>' + precos_madeira[i][0] + ":::" + precos_madeira[i][1] + "--" + precos_madeira[i][2] + "--" + precos_madeira[i][3] + "--" + precos_madeira[i][4]+"</li>";
}
text += "</ul>";
document.getElementById("pp").innerHTML = text;
}
//------CHARTS---------//
function drawChart() {
// Define the chart to be drawn.
var data = new google.visualization.DataTable();
data.addColumn('string', 'Month');
data.addColumn('number', 'Madeira');
data.addColumn('number', 'Argila');
data.addColumn('number', 'Ferro');
data.addColumn('number', 'PPs na conta');
data.addRows(precos_madeira);
// Set chart options
var options = {'title' : 'Average Temperatures of Cities',
hAxis: {
title: 'Month'
},
vAxis: {
title: 'Temperature'
},
'width':550,
'height':400,
pointsVisible: true
};
// Instantiate and draw the chart.
var chart = new google.visualization.LineChart(document.getElementById('container'));
chart.draw(data, options);
}
google.charts.setOnLoadCallback(drawChart);
</script>
</body>
</html>
Related
I have this program where there are a series of registered students and when they put their name, their data and the name of the teacher they have assigned.
When inserting a new student, the only thing that it does to me correctly is to print if the teacher exists or not, since the student's data does not show them to me, and finally I have a failure in the last line of the javascript code related to innerhtml , the error in question is:
Uncaught TypeError: Cannot set properties of null (setting
'innerHTML')
at mensaje.js:74
now the code:
html:
<button onclick="infoalumno()">Informacion del alumno</button>
<button onclick="insertar()">Introducir nuevo alumno</button>
<div id="info"></div>
and javascript code:
function alumno(nombre, edad, nota, profesor) {
this.nombre = nombre;
this.edad = edad;
this.nota = nota;
this.profesor = profesor;
}
function profesor(nombre, asginatura) {
this.nombre = nombre;
this.asginatura = asginatura;
}
var profesores = new Array(3);
profesores[0] = new profesor("Paco","Plastica");
profesores[1] = new profesor("Anton","Biologia");
profesores[2] = new profesor("Jacinto","Lengua");
var alumnos = new Array(2);
alumnos[0] = new alumno("Jose",24,7,profesores[0]);
alumnos[1] = new alumno("Jacobo",23,7,profesores[2]);
function infoalumno() {
var buscar = prompt("Inserta el nombre del alumno que quieres buscar");
var comprobar = false
for (let i = 0; i < alumnos.length; i++) {
if (buscar == alumnos[i].nombre) {
document.write("Nombre" + alumnos[i].nombre + "<br>Edad:" + alumnos[i].edad + "<br>Nota:" + alumnos[i].nota + "<br>Profesor:" + alumnos[i].profesor.nombre);
comprobar = true;
}
if (comprobar == false) {
document.write("Alumno " + buscar + "no existe");
}
}
}
function insertar() {
var comprobar2 = false;
var nombre = prompt("Insertar el nombre del alumno");
var edad = parseInt(prompt("Ingresa la edad"));
var nota = parseInt(prompt("Ingresa la nota"));
var profesor = prompt("¿Quien es el profesor?");
for (let i = 0; i < profesores.length; i++) {
if (profesor == profesores[i].nombre) {
var newalumno = new alumno(nombre, edad, nota, profesor[i]);
alumnos.push(newalumno);
comprobar2=true;
break;//la sentencia break permite terminar de forma abrupta un bucle y la sentencia continue permite saltarse algunas repeticiones del bucle. ... La utilidad de break es terminar la ejecución del bucle cuando una variable toma un determinado valor o cuando se cumple alguna condición.
}
}
if(comprobar2==false){
document.write("Profesor "+profesor+" no existe");
}
}
var infoprofesor ="Profesores";
for (let i = 0; i < profesores.length; i++) {
infoprofesor = infoprofesor + profesores[i].nombre+"<br>";
}
document.getElementById("info").innerHTML = infoprofesor;
1)
The teacher does not appear his name instead appears [object Object]
In this code
document.write("Nombre" + alumnos[i].nombre + "<br>Edad:" + alumnos[i].edad + "<br>Nota:" + alumnos[i].nota + "<br>Profesor:" + alumnos[i].profesor);
This alumnos[i].profesor will be a Profesor object like from calling new Profesor(...). If you wanted to show the name it would look like alumnos[i].profesor.nombre
2)
And when inserting a new student, the only thing that it does to me
correctly is to print if the teacher exists or not.
var profesor = prompt("¿Quien es el profesor?");
for (let i = 0; i < profesores.length; i++) {
if (profesor == profesores[i].nombre) {
var newalumno = new alumno(nombre, edad, nota, profesor);
alumnos.push(newalumno);
comprobar2=true;
break;
}
}
In this loop you have a related issue. The result from prompt will just be a string (your var profesor). However when you go to make your new alumno it expects a profesor object (with nombre/asignatura).
In this case you're probably want to do var newalumno = new alumno(nombre, edad, nota, profesores[i]);
with Google Script i have created this html that send datas to a google sheet taking in input some data from the url (after /exec?P=tonno&Q=3&C=Cliente+1 he takes in input P,Q,C):
<!DOCTYPE html>
<html>
<head>
<title> Modulo di Ordine </title>
<script type="text/javascript">
function doGet(e){
//HtmlService.setTitle("This is MYTITLE");
var result = '<-- Riepilogo Ordine --> \n';
if (e.parameter == 'undefined') {
result += "ERRORE SCONOSCIUTO NELL'ACQUISTO! non verrà inviato l'ordine";
return ContentService.createTextOutput(result);
}
else {
var ID = '1sl0P4auOdX8i67kZ9LA8dGXm59I_fc_tSOaPaOpL1Ek'; // identificativo della cartella di foglio (Spreadsheet ID)
// var sheet = SpreadsheetApp.openById(sheet_id).getActiveSheet();
// var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var Cartella = SpreadsheetApp.openById(ID); // Cartella identificata da ID
var Foglio = Cartella.getSheets()[0]; // nella parentesi quadra il foglio ---> 0 = primo, 1 = secondo, ecc.
var Cella_R = Foglio.getRange(2,5); // riga 2, colonna 5 -> cella E2
var Inserite = Cella_R.getValue() + 1; // numero di righe inserite (letto dal foglio) incrementato di 1
Cella_R.setValue(Inserite); // scrive nel fogio il valore incrementato di «Inserite»
// var Riga = Foglio.getLastRow() + 1;
var Riga = Inserite + 2; // Riga in cui scrivere i dati
result += 'Codice Ordine: #' + Riga; // calcola la riga su cui scrivere i dati
var Cella_D = Foglio.getRange(Riga,1); // D = Data --------------> colonna 1
var Cella_O = Foglio.getRange(Riga,2); // O = Orario ------------> colonna 2
var Cella_T = Foglio.getRange(Riga,3); // T = Temperatura -------> colonna 3
var Cella_U = Foglio.getRange(Riga,4); // U = Umidità relativa --> colonna 4
var Cella_C = Foglio.getRange(Riga,5); // C = Cliente ----------->
var answer = "";
// SpreadsheetApp.setActiveSheet(sheet);
// var rowData = [];
var Giorno_Ora = new Date(); // legge data ed ora attuali
var Data = Utilities.formatDate(Giorno_Ora, "Europe/Rome", 'dd/MM/yyyy'); // estrae la data da Data_Ora
var Orario = Utilities.formatDate(Giorno_Ora, "Europe/Rome", 'HH.mm.ss' ); // estrae l'orario da Data_Ora
Cella_D.setValue(Data); //scrive la Data
Cella_O.setValue(Orario); //scrive l'orario
for (var parametro in e.parameter) {
var valore = Pulisci(e.parameter[parametro]); //estrae il valore del paramentro senza virgolette
switch (parametro) { // condizione case
case 'P':
Cella_T.setValue(valore); // Scrive il prodotto
result += '\nProdotto: ' + valore + ''; // Scrive messaggio risposta
break;
case 'C':
Cella_C.setValue(valore); // Scrive il cliente
result += '\nCliente: ' + valore + ''; // Scrive messaggio risposta
break;
case 'Q':
Cella_U.setValue(valore); // Scrive la quantità
result += '\nQuantità: ' + valore + ' pezzi'; // Scrive messaggio risposta
break;
default: //in caso di errore:
result += "\n\nParametri non validi!. L'ordine non verrà preso in considerazione";
}
} //se tutto va bene passa avanti con il successo
result += '\n\nEseguito con successo! Qualcuno provvederà a prendere in considerazione il suo ordine.';
}
return ContentService.createTextOutput(result); // Restituisce il Riepilogo dell'ordine
}
function Pulisci( value ) {
return value.replace(/^["']|['"]$/g, ""); // sostituisce cosa a cosa???
}
</script>
</head>
<body>
<p>Sicuro di voler procedere con l'ordine?</p> <br>
<input id="clickMe" type="button" value="clickme" onclick="doGet();" />
</body>
</html>
The problem is that when I press the button to call the function doGet(), this is the error and the function doesn't go on:
userCodeAppPanel:5 Uncaught TypeError: Cannot read property 'parameter' of undefined
at doGet (userCodeAppPanel:5)
at HTMLInputElement.onclick (userCodeAppPanel:1)
Can pls somebody help me?
ContentService, SpreadsheetApp, and even doGet(e) are server side functions they run on a Google Server not on your browser. You need to restructure your entire code and utilize some intermediate javascript functions and possibly google.script.run you would be well served to do a little more research in some of the examples provided here at SO.
The idea of using doGet(e) as a clientside function is rather ridculuous because the whole idea is that it's supposed to be an endpoint on the server. It's ridiculous to consider it as a clientside function.
To resolve the issue you are facing, you need to change your button HTML element to the below code -
<input id="clickMe" type="button" value="clickme" onclick="doGet(event);" />
Since you are using inline event handler, you need to pass the event as argument to onClick method. Please refer to this post in-case you have any queries.
I'm looking for help for a function in javascript or via the jquery framework which seems easy but I can't. I want to display a "p" tag according to a value present in the document, this value is dynamic.
Here is what I tried:
html
<label class="labeltal">Types of Course:
<p style="display: none;" id="shortc" value="1">SHORT COURSE</p>
<p style="display: none;" id="medco" value="2">MEDIUM COURSE</p>
<p style="display: none;" id="lonco" value="3">LONG COURSE</p>
</label>
<td colspan="2" rowspan="2">
<div class="d-inline-flex">
<p class="MinRounds" id="nbcp" name="MinRounds" onkeyup="noumberCoups(event)"></p>
</div>
</td>
javascript test 1
<script>
function noumberCoups(event) {
var nbCoups = event.target.value;
if (nbCoups > 25){
document.getElementById("lonco").style.display = "block";
}else if(nbCoups >= 25){
document.getElementById("medco").style.display = "block";
} else {
document.getElementById("shortc").style.display = "block";
}
console.log(nbCoups);
};
</script>
javascript test 2
<script>
let nbCoups = document.getElementById("nbcp").textContent;
//let nbCoups = $('#nbcp').text();
let p = document.getElementById('nbcp');
let text = p.textContent;
let nbCoups = Number(text);
if (nbCoups > 25) {
document.getElementById("lonco").style.display = "block";
}else if(nbCoups >= 25){
document.getElementById("medco").style.display = "block";
}else{
document.getElementById("shortc").style.display = "block";
}
</script>
javascript test 3
<script>
let nbCoups= $('#nbcp').text();
if (nbCoups> 25) {
document.getElementById("lonco").style.display = "block";
}else if(nbCoups>= 25){
document.getElementById("medco").style.display = "block";
}else{
document.getElementById("shortc").style.display = "block";
}
</script>
javascript incremented value id="nbcp"
$(document).ready(function() {
let nbcoup = 0;
document.getElementById("nbcp").innerText = nbcoup;
let pts = 0;
document.getElementById("point").innerText = pts;
../..
$('.draggable').draggable({
helper: 'clone',
cursor: 'move',
scope: "#paper , #metal , #decor",
grid: [2, 1],
})
$("#dropzone").droppable({
scope: "#paper , #metal , #decor",
drop: function(event, ui) {
if (ui.draggable.attr("alt") == "target")
{
n = 1;
p = 5;
pap++;
}
../..
nbcoup = nbcoup + n;
pts = pts + p;
document.getElementById("nbcp").innerText = nbcoup;
../..
}
../..
Thank you!
It's unnecessary to have different p tags for the different cases.
It would be better to change the content of the tag dynamically.
Here's how you could do it.
I created the event object since I don't know where you are getting it and I replaced the value in the 'Medium' option since it was the same as the 'Long' one.
let t = {
target: { value: 30 }
}
function noumberCoups(event) {
var nbCoups = event.target.value;
const p = document.getElementById('course-type');
if (nbCoups > 25){
p.innerHTML = 'Long course'
} else if(nbCoups >= 15){
p.innerHTML = 'Medium course'
} else {
p.innerHTML = 'Short course'
}
console.log(nbCoups);
};
noumberCoups(t);
<label class="labeltal">Types of Course: <p id="course-type"></p>
</label>
Is pretty simple, step:
Create function
Add onChange to input (i use input for snippet)
In the function add option to select
optional : add function for remove option (just for snippet)
Example:
Full code by codepen (this snippet only work with your codepen):
$(document).ready(function() { //fonction qui exectute le script
//console.log(document);
const selectbox = document.getElementById("ConditionCourseId");
let nbcoup = 0; //Nombre de coup
document.getElementById("nbcp").innerText = nbcoup;
let pts = 0; //Nombre de points
document.getElementById("point").innerText = pts;
let pap = 0; //Nombre de cible papier
document.getElementById("papier").innerText = pap;
let met = 0; //Nombre de métal
document.getElementById("metal").innerText = met;
let minipap = 0; //Nombre de cible papier
document.getElementById("minipapier").innerText = minipap;
let minimet = 0; //Nombre de métal
document.getElementById("minimetal").innerText = minimet;
let plt = 0; //Nombre de métal poper
document.getElementById("plate").innerText = plt;
let bob = 0; //Nombre de métal minipoper
document.getElementById("bobber").innerText = bob;
let nosh = 0; //Nombre de noshoot
document.getElementById("targetNS").innerText = nosh;
let n = 0;
let p = 0;
let decorsvg = document.getElementById("decorsvg")
$('.draggable').draggable({ //fonction qui rend les elements draggable
helper: 'clone',
cursor: 'move',
scope: "#paper , #metal , #decor",
grid: [2, 1],
// handle: "draggable"
})
$("#dropzone").droppable({ //fonction qui rend la zone droppable
//accept: "#objet1, #objet2 , #objet3 , #objet4",
scope: "#paper , #metal , #decor",
drop: function(event, ui) { //fonction qui gere les evenements de drop
if (ui.draggable.attr("alt") == "popper") {
n = 1;
p = 5;
met++;
} else if (ui.draggable.attr("alt") == "minipopper") {
n = 1;
p = 5;
minimet++;
} else if (ui.draggable.attr("alt") == "plate") {
n = 1;
p = 5;
plt++;
} else if (ui.draggable.attr("alt") == "target") {
n = 2;
p = 10;
pap++;
} else if (ui.draggable.attr("alt") == "minitarget") {
n = 2;
p = 10;
minipap++;
} else if (ui.draggable.attr("alt") == "bobber") {
n = 2;
p = 10;
bob++;
} else if (ui.draggable.attr("alt") == "targetNS") {
n = 0;
p = 0;
nosh++;
} else {
n = 0;
p = 0;
}
nbcoup = nbcoup + n;
pts = pts + p;
document.getElementById("nbcp").innerText = nbcoup; //ligne qui pemettent d'écrire dans le tableau en positif
Which(nbcoup);
function Which(el){
removeOption(selectbox);
let newOption = new Option();
if (el > 25) {
newOption.text='LONG COURSE';
newOption.value='3';
newOption.id="lonco";
}else if(el == 25){
newOption.text='MEDIUM COURSE';
newOption.value='2';
newOption.id="medco";
}else{
newOption.text='SHORT COURSE';
newOption.value='1';
newOption.id="shortc";
}
selectbox.add(newOption);
}
document.getElementById("point").innerText = pts;
document.getElementById("metal").innerText = met;
document.getElementById("papier").innerText = pap;
document.getElementById("minimetal").innerText = minimet;
document.getElementById("minipapier").innerText = minipap;
document.getElementById("plate").innerText = plt;
document.getElementById("bobber").innerText = bob;
document.getElementById("targetNS").innerText = nosh;
let redrag = $(ui.helper).clone().removeClass('draggable') //variable qui enleve la class du l'élément cloné et qui redonne la fontion draggable aux clones
redrag.draggable({
containment: 'parent',
cursor: 'move',
grid: [2, 2],
snap: true,
snapTolerance: 5,
});
//fonction qui permet de mettre l'image au premier avec z-index
$(this).append(redrag);
$("img").click(function() {
let maxZindex = 0;
$("img").each(function() {
let z = parseInt($(this).css('z-index'));
if (isNaN(z)) z = 0;
if (z > maxZindex) maxZindex = z;
});
//attribuer un z-index supérieur à l'élément cliqué
$(this).css('z-index', maxZindex + 1);
});
//fonction qui permet de mettre le svg au premier avec z-index
$(this).append(redrag);
$("svg").click(function() {
// console.log(this) ;
let maxZindex = 0;
$("svg").each(function() {
let z = parseInt($(this).css('z-index'));
if (isNaN(z)) z = 0;
if (z > maxZindex) maxZindex = z;
});
//attribuer un z-index supérieur à l'élément cliqué
$(this).css('z-index', maxZindex + 1);
});
if ( $(this).find("img").addClass("removable") ) { //fonction qui permet d'ajouter une class a l'image pour la supprimer avec le button reset
};
if ( $(this).find("svg").addClass("removable") ) { //fonction qui permet d'ajouter une class a le svg pour la supprimer avec le button reset
};
$(this).find("svg").dblclick(function() { //fonction qui supprime un élément svg de la zone droppable par l'action double click
$(this).remove();
});
$(this).find("img").dblclick(function() { //fonction qui supprime un élément image de la zone droppable par l'action double click
$(this).remove();
if (ui.draggable.attr("alt") == "popper") {
n = 1;
p = 5;
met--;
} else if (ui.draggable.attr("alt") == "minipopper") {
n = 1;
p = 5;
minimet--;
} else if (ui.draggable.attr("alt") == "plate") {
n = 1;
p = 5;
plt--;
} else if (ui.draggable.attr("alt") == "target") {
n = 2;
p = 10;
pap--;
} else if (ui.draggable.attr("alt") == "minitarget") {
n = 2;
p = 10;
minipap--;
} else if (ui.draggable.attr("alt") == "bobber") {
n = 2;
p = 10;
bob--;
} else if (ui.draggable.attr("alt") == "targetNS") {
n = 0;
p = 0;
nosh--;
} else {
n = 0;
p = 0;
}
nbcoup = nbcoup - n;
pts = pts - p;
document.getElementById("nbcp").innerText = nbcoup; //ligne qui pemettent d'écrire dans le tableau en négatif
document.getElementById("point").innerText = pts;
document.getElementById("metal").innerText = met;
document.getElementById("papier").innerText = pap;
document.getElementById("minimetal").innerText = minimet;
document.getElementById("minipapier").innerText = minipap;
document.getElementById("plate").innerText = plt;
document.getElementById("bobber").innerText = bob;
document.getElementById("targetNS").innerText = nosh;
});
}
});
$("#reset").on("click", function() { // fonction du boutton reset pour supprmer tout les elements clone draggés dans la zone possedant la classe removable
$('.removable').remove();
nbcoup = 0;
pts = 0;
met = 0;
minimet = 0;
plt = 0;
pap = 0;
minipap = 0;
bob = 0;
nosh = 0;
document.getElementById("nbcp").innerText = nbcoup; //ligne qui pemettent d'écrire dans le tableau a zéro
document.getElementById("point").innerText = pts;
document.getElementById("metal").innerText = met;
document.getElementById("papier").innerText = pap;
document.getElementById("minimetal").innerText = minimet;
document.getElementById("minipapier").innerText = minipap;
document.getElementById("plate").innerText = plt;
document.getElementById("bobber").innerText = bob;
document.getElementById("targetNS").innerText = nosh;
exit();
});
});
$("#elements").accordion({ //Fonction pour la liste déroulante des cibles et accessoires
collapsible: true,
heightStyle: "fill"
});
$( "#accordion-resizer" ).resizable({
resize: function() {
$( "#elements," ).accordion( "refresh" );
}
});
//script pour capturer l'image du stage
function uploadFile() {
window.scrollTo(0, 0); //scroll page entiere du haut en bas
html2canvas(document.getElementById("main"),{scale: 2}).then(function(canvas){ //creation image avec scale: 2-> qualité X2
let doc = new jsPDF();
// doc.setFontSize(40); //taille titre
// doc.text(40, 25, "TSV STAGE MAKER") // titre
doc.addImage(canvas.toDataURL("image/jpeg", 0.9), 'JPEG', 5, 10, 200, 270); //'JPEG', 15(Gauche), 10 (Haut), 180 (Droite), 280 (Bas)
let blob = doc.output('blob');
let image = ("image=" + canvas.toDataURL("image/jpeg", 0.9));
let stagename = document.querySelector('[name="stagename"]');
let stagenumber = document.querySelector('[name="stagenumber"]');
let FirearmId = document.querySelector('[name="FirearmId"]');
let TrgtTypeId = document.querySelector('[name="TrgtTypeId"]');
let ScoringId = document.querySelector('[name="ScoringId"]');
let StartOn = document.querySelector('[name="StartOn"]');
let StartPos = document.getElementById("StartPos");
let Descriptn = document.getElementById("Descriptn");
let CourseId = document.querySelector('[name="CourseId"]');
let MatchsId = document.querySelector('[name="MatchsId"]');
let MaxPoints = document.querySelector('[name="MaxPoints"]');
let MinRounds = document.querySelector('[name="MinRounds"]');
let TrgtPaper = document.querySelector('[name="TrgtPaper"]');
let TrgtPlates = document.querySelector('[name="TrgtPlates"]');
let TrgtPenlty = document.querySelector('[name="TrgtPenlty"]');
let TrgtPopper = document.querySelector('[name="TrgtPopper"]');
let bobber = document.getElementById("bobber");
let StringCnt = document.querySelector('[name="StringCnt"]');
let ReportOn = document.querySelector('[name="ReportOn"]');
let Token = document.querySelector('[name="_token"]');
let sectionstage = document.getElementById("datastage");
let formData = new FormData();
formData.append('file', blob);
formData.append('jpeg', image);
formData.append('stagename', stagename.value);
formData.append('stagenumber', stagenumber.value);
formData.append('FirearmId', FirearmId.value);
formData.append('TrgtTypeId', TrgtTypeId.value);
formData.append('ScoringId', ScoringId.value);
formData.append('StartOn', StartOn.value);
formData.append('StartPos', StartPos.innerText);
formData.append('Descriptn', Descriptn.innerText);
formData.append('CourseId', CourseId.value);
formData.append('MatchsId', MatchsId.value);
formData.append('MaxPoints', MaxPoints.innerText);
formData.append('MinRounds', MinRounds.innerText);
formData.append('TrgtPaper', TrgtPaper.innerText);
formData.append('TrgtPlates', TrgtPlates.innerText);
formData.append('TrgtPenlty', TrgtPenlty.innerText);
formData.append('TrgtPopper', TrgtPopper.innerText);
formData.append('bobber', bobber.innerText);
formData.append('StringCnt', StringCnt.value);
formData.append('ReportOn', ReportOn.value);
formData.append('_token', Token.value);
formData.append('datastage', sectionstage.innerHTML);
console.log(formData);
let xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if(this.readyState == 4 && this.status == 200) {
alertify.success('Your Stage has been successfully saved !');
return;
}
}
xhr.open("post", "{{ path('app_stage_create') }}",);
xhr.send(formData);
});
}
// script pour telecharger le pdf direct sur pc
function savPDF(){
window.scrollTo(0, 0);
html2canvas(document.getElementById("main"),{scale: 2}).then(function(canvas){
let doc = new jsPDF();
// doc.setFontSize(5);
// doc.text(40, 25, "text")
doc.addImage(canvas.toDataURL("image/jpeg", 0.9), 'JPEG', 5, 10, 200, 320);//'JPEG', 15(Gauche), 10 (Haut), 180 (Droite), 280 (Bas)
doc.save("stage.pdf");
});
};
// change COULEURS PANNEAU
// change COULEURS PANNEAU
function changeColor(){
let color = document.getElementById('colorInputColor').value;
$("svg rect").each(function() {
$(".panneau1").css("fill", color);
});
}
//rotation elements
let degrees = 0;
$(".elementRotate").click(function () {
degrees += 10;
$(this).css("transform", "rotate(" + degrees + "deg)");
});
function removeOption(el) {
while (el.options.length > 0) {
el.remove(0);
}
}
<label class="labeltal">Types of Course:
<select class="noborder font-weight-bold" name="CourseId" id="ConditionCourseId"
</select>
I realise an alphabetic search of products. At the click on letter, all products begining by the letter is displaying.
But i would diplay it at the top of the letter and hide before.
Did i have to used functions hover() and append() ans how ?
that's my code :
_alphabets.hover(function(){
var _letter = $x(this), _text = $x(this).text(), _count = 0;
_contentRows.removeClass("lignetrouve");
_contentRows.each(function(i) {
var _cellText = $x(this).children('td').eq(0).text();
if ( RegExp('^' + _text).test(_cellText) ) {
_count += 1;
list = $x(this).addClass("lignetrouve");
}
}); /*end _contentRows.each(function(i) */
//we count number of child
_nblignes = $x('.lignetrouve').length;
//display
$x('.compteur').append(_nblignes);
})
Thanks.
I found :
_alphabets = $x('.alphabet > a');
_contentRows = $x('#produits-table tbody tr');
_alphabets.click(function() {
var _letter = $x(this), _text = $x(this).text(), _count = 0;
//Ajout de la class active a la lettre plutot qu'a l'alphabet entier
_alphabets.removeClass("active");
_letter.addClass("active");
_contentRows.removeClass("lignetrouve");
if (($x('#noproduct').length == 0) && ($x('.lignetrouve').length == 0)) {
$x('tbody').append('<tr id="noproduct"><td>Aucun produit</td></tr>');
};
_contentRows.hide();
_contentRows.each(function(i) {
//Affectation de la variable celltext qui contient le contenu
var _cellText = $x(this).children('td').eq(0).text();
//Si le debut commence comme la lettre selectionnée
if ( RegExp('^' + _text).test(_cellText) ) {
_count += 1;
list = $x(this).fadeIn(400);
list.addClass("lignetrouve");
$x('#noproduct').remove();
}
_nblignes = $x('.lignetrouve').length;
$x(this).attr('data-title',_nblignes);
}); /*end _contentRows.each(function(i) */
}); /*end _alphabets.click(function() */
_alphabets.hover(function(){
_contentRows.removeClass("lignetrouve");
var _letter = $x(this), _text = $x(this).text(), _count = 0;
_contentRows.each(function(i) {
var _cellText = $x(this).children('td').eq(0).text();
if ( RegExp('^' + _text).test(_cellText) ) {
_count += 1;
//on ajoute une class pour le calcul
list = $x(this).addClass("lignetrouve");
}
}); /*end _contentRows.each(function(i) */
_nblignes = $x('.lignetrouve').length;
$x(this).attr('data-title',_nblignes);
}); /*end _alphabets.hover(function() */
Jsfiddle
I need to use the same JavaScript function called Cerca2 in 3 separated selects. The first one works, but the others do not. I've tried to fix the problem by myself but I can't find where it is.
EDIT: code edited, now work perfectly, tnx for all the suggestion and support guys ^^
This is the html:
<body>
Ricerca per Nome: <input type="text" maxlength="20"/>
<input id="cerca1" type="button" value="Cerca" /><br/><br/>
Ricerca personaggi per Fazione:
<select id="factionSelect">
<option>UNSC</option>
<option>Covenant</option>
<option>Flood</option>
<option>Precursori</option>
</select> <input id="cerca2" selectid="factionSelect" type="button" value="Cerca"/>
<br/><br/>
Ricerca armi per tipo:
<select id="weaponSelect">
<option>cinetiche</option>
<option>plasma</option>
<option>energia</option>
</select> <input id="cerca5" selectid="weaponSelect" type="button" value="Cerca"/>
<br/><br/>
Ricerca Veicoli per impiego:
<select id="vehicleSelect">
<option>terrestri</option>
<option>volanti</option>
<option>Astronavi</option>
</select> <input id="cerca6" selectid="vehicleSelect" type="button" value="Cerca"/>
<input id="cerca3" type="button" value="Mostra tutto"/>
<input id="cerca4" type="button" value="Ricerca casuale"/><br/><br/>
<hr id="barra"/><br/><p>Risultati ricerca:</p>
<div id="risultati">
<ol id="ricerca">
<li class="vuoto"></li>
</ol>
</div>
</body>
This is the JavaScript:
function Profilo(nom, appar, prof, grup, img){
this.nome = nom;
this.apparizione = appar;
this.profilo = prof;
this.gruppo = grup;
this.immagine = img;
}
function Archivio(){
this.lista = [];
this.inizializza = function(nodo){
var schede = nodo.getElementsByTagName("scheda");
for(var i = 0; i<schede.length; i++){
var categoria = schede[i].getAttribute("categoria");
var nomi = schede[i].getElementsByTagName("nome");
var nome = nomi[0].firstChild.nodeValue;
var apparizioni = schede[i].getElementsByTagName("apparizione");
var apparizione = apparizioni[0].firstChild.nodeValue;
var profili = schede[i].getElementsByTagName("profilo");
var profilo = profili[0].firstChild.nodeValue;
var immagini = schede[i].getElementsByTagName("immagine");
var immagine = immagini[0].firstChild.nodeValue;
var scheda = new Profilo(nome, apparizione, profilo, categoria,immagine);
this.lista.push(scheda);
}
}
this.cerca1 = function(testo){
var risultato = [];
var trovato = 0;
var i = 0;
while(i<this.lista.length && trovato == 0){
if(this.lista[i].nome == testo)
{
trovato = 1;
risultato.push(this.lista[i]);
}
else
i++;
}
if(trovato == 1)
return risultato;
else
{
risultato[0] = null;
return risultato;
}
}
this.cerca2 = function(testo){
var risultati = [];
for(var i = 0; i<this.lista.length; i++){
if(this.lista[i].gruppo == testo)
risultati.push(this.lista[i]);
}
return risultati;
}
this.cerca3 = function(numero){
var risultati = [];
risultati.push(this.lista[numero]);
return risultati;
}
this.genera = function(valori){ // genera la lista con gli elementi di xml
var s = "";
if(valori[0] == null)
s = "Nessun risultato";
else{
for(var i = 0; i<valori.length; i++)
s = s + '<li><span class="trovato" onclick="mostra(this);">' + valori[i].nome + " " + '</span><br/><ol class="nascosto"><li class="nopallino2"> <img src='+ valori[i].immagine+'> <br/><br/>Profilo: '+ valori[i].profilo +'<br/>Apparizione: ' + valori[i].apparizione +'</li></ol></li><br/><br/>';
}
return s;
}
this.nascondi = function(){
var liste = document.getElementsByTagName("ol");
for(var i = 0; i<liste.length; i++){
if(liste[i].className == "nascosto")
liste[i].style.display = "none";
}
}
}
function cercagruppo(){
/*var elenco = document.getElementById("ricerca");
var menu = document.getElementsByTagName("select");
var scelta = menu[0];
var gruppo = scelta.value;
var schede = contenitore.cerca2(gruppo);
elenco.innerHTML = contenitore.genera(schede);
contenitore.nascondi(); */
var elenco = document.getElementById("ricerca");
var menu = document.getElementById(this.getAttribute("selectid"));
var group = menu.value;
var schede = contenitore.cerca2(group);
elenco.innerHTML = contenitore.genera(schede);
contenitore.nascondi();
}
function mostra(nome){
var testo = nome.nextSibling.nextSibling;
if(testo.style.display == "none")
testo.style.display = "block"
else
testo.style.display = "none"
}
// funzione che cerca le schede relative all'oggetto cercato digitando il nome
function cercanome(){
var casella = document.getElementsByTagName("input");
var nome;
var elenco = document.getElementById("ricerca");
var scheda;
nome = casella[0].value;
scheda = contenitore.cerca1(nome);
elenco.innerHTML = contenitore.genera(scheda);
contenitore.nascondi();
}
// funzione per mostrare tutte le schede
function tutto(){
var elenco = document.getElementById("ricerca");
elenco.innerHTML = contenitore.genera(contenitore.lista);
contenitore.nascondi();
}
function generaCasuale(){
var numerogenerato = Math.floor(Math.random()*(parseInt(contenitore.lista.length-1)+1));
if(numerogenerato == randomglobale){
while(numerogenerato == randomglobale)
numerogenerato = Math.floor(Math.random()*(parseInt(contenitore.lista.length-1)+1));
}
randomglobale = numerogenerato;
return numerogenerato;
}
// funzione di ricerca casuale
function casuale(){
var elenco = document.getElementById("ricerca");
var numero = generaCasuale();
var scheda = contenitore.cerca3(numero);
elenco.innerHTML = contenitore.genera(scheda);
contenitore.nascondi();
}
var contenitore = new Archivio();
var randomglobale;
function inizializza(){
var c1 = document.getElementById("cerca1");
var c2 = document.getElementById("cerca2");
var c3 = document.getElementById("cerca3");
var c4 = document.getElementById("cerca4");
var c5 = document.getElementById("cerca5");
var c6 = document.getElementById("cerca6");
c1.onclick = cercanome;
c2.onclick = cercagruppo;
c3.onclick = tutto;
c4.onclick = casuale;
c5.onclick = cercagruppo;
c6.onclick = cercagruppo;
var nodo = caricaXML("elenco.xml");
contenitore.inizializza(nodo);
}
window.onload = inizializza;
I'm not sure I totally understand the question, but in this code, c5 and c6 are all getting the cerca2 inputs :
var c1 = document.getElementById("cerca1");
var c2 = document.getElementById("cerca2");
var c3 = document.getElementById("cerca3");
var c4 = document.getElementById("cerca4");
var c5 = document.getElementById("cerca2");
var c6 = document.getElementById("cerca2");
In several parts of your code, you select all elements of a certain type, but only use the first such element.
For example:
function cercagruppo(){
...
var menu = document.getElementsByTagName("select"); // gets all "select" elements
var scelta = menu[0]; // gets value of first "select" element
...
}
And also:
function cercanome(){
var casella = document.getElementsByTagName("input"); // gets all "input" elements
...
nome = casella[0].value; // gets value of first "input" element
...
}
If you want to get the values from all select and input elements, you'll need to do so explicitly, such as by looping through the menu and casella arrays instead of selecting only their first items.
Edit: Suggested approach to refactoring code
Having looked at your code a bit more, here's the approach I think you should take:
In your HTML, add an ID attribute to each of your select elements.
Add an attribute to your "cerca2", "cerca5", and "cerca6" input buttons that indicates the ID of the corresponding select element
You can then access the attribute in the cercagruppo() function and use it to select the corresponding select element.
Your cercagruppo() function would look more like this:
function cercagruppo(){
var ol = document.getElementById("ricerca");
var selection = document.getElementById(this.getAttribute("selectid"));
var group = selection.value;
var tabs = contenitore.cerca2(group);
ol.innerHTML = contenitore.genera(tabs);
contenitore.nascondi();
}
Your HTML would end up looking more like this:
Ricerca personaggi per Fazione:
<select id="factionSelect">
<option>UNSC</option>
<option>Covenant</option>
<option>Flood</option>
<option>Precursori</option>
</select> <input id="cerca2" selectid="factionSelect" type="button" value="Cerca"/>
<br/><br/>
Ricerca armi per tipo:
<select id="weaponSelect">
<option>cinetiche</option>
<option>plasma</option>
<option>energia</option>
</select> <input id="cerca5" selectid="weaponSelect" type="button" value="Cerca"/>
<br/><br/>
Ricerca Veicoli per impiego:
<select id="vehicleSelect">
<option>terrestri</option>
<option>volanti</option>
<option>Astronavi</option>
</select> <input id="cerca6" selectid="vehicleSelect" type="button" value="Cerca"/>
Edit edit
And of course, you should also fix the error that #mgarant pointed out:
var c1 = document.getElementById("cerca1");
var c2 = document.getElementById("cerca2");
var c3 = document.getElementById("cerca3");
var c4 = document.getElementById("cerca4");
var c5 = document.getElementById("cerca5"); // fixed
var c6 = document.getElementById("cerca6"); // fixed