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
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]);
I am building a shopping cart and I am having issue getting the total amount of it.
let calculPrice = [];
for (productLocalStorage of productLocalStorage) {
let article = productLocalStorage.prix;
calculPrice.push(article);
};
const reducer = (accumulator, currentValue) => accumulator + currentValue;
const totalPrice = calculPrice.reduce(reducer, 0);
console.log(totalPrice);
To get the total amount I've created a loop which work fine but I have an error when I try to delete an item
"cart.js:77 Uncaught TypeError: productLocalStorage.indexOf is not a function
at HTMLButtonElement.<anonymous> (cart.js:77)"
This is my event from my delete button
let reachDeleteButton = document.querySelectorAll(".product-delete");
console.log(reachDeleteButton);
//Creation d'un tableau vide
let tab = [];
for (let i = 0; i < reachDeleteButton.length; i++){
reachDeleteButton[i].addEventListener("click", (event) => {
event.preventDefault();
//Récupération de l'index du produit associé au bouton supprimer
let getIndexOnLocalStorage = productLocalStorage.indexOf(productLocalStorage[i]);
console.log(getIndexOnLocalStorage);
tab = productLocalStorage
let response = confirm("Vous allez retirer ce produit de votre panier, voulez-vous continuer?")
if (response == true ) {
tab.splice(getIndexOnLocalStorage, 1)
productLocalStorage = localStorage.setItem("product", JSON.stringify(tab));
window.location.href ="cart.html";}
else {
}
})
}
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>
CODEPEN: https://codepen.io/3lly/pen/LYNzJwP
I have an array of objects:
let product = [
{omschrijving:"Brood", waarde:1, aantal:3, total:0},
{omschrijving:"Brocolli", waarde:0.99, aantal:2, total:0},
{omschrijving:"Krentenbollen", waarde:1.20, aantal:4, total:0},
{omschrijving:"Noten", waarde:2.99, aantal:2, total:0}
]
And I generate a table, I added an extra column with a number input field. I want the property of aantal set in the value of the number input field.
With these loops (I did the loop again because a scoping issue?) I get the last value only in ALL of the fields. So they all fill in 2.
var elements = table.getElementsByTagName('input');
for(let j=0;j<elements.length;j++) {
for(let i=0;i<product.length;i++) {
let = elements[j].value = product[i].aantal;
}
}
The expected output is in the first input field it would be 3, the next, 2,4,2
I will also put the snippet here so you can see the result.( I know it is a mess right now)
UPDATE , I did get it finally, it took me hours I dont even really completely understand. But I gave a rowID with the generation of the row and compare it to that. I tried so many things. I have a lot to do on this code. Now to make it increment etc. etc.
Now my problem is that I cannot increment and update the value of products.aantal This so it can calculate the total. If I can get that to work I can fix the rest.
It somehow does not see the products.value in the loop of EentjeMeer Function.
Because that loop worked before I wanted to do the same loop but now of course just increment the "aantal" column. My head hurts :/ been at it for many hours today.
I added this, but I will update my snippet:
var elements = table.getElementsByTagName('input');
schaap = [];
for(let j=0;j<elements.length;j++) {
inputID++;
//console.log("de input ID" + inputID);
//product.push({input: elements[j]});
//console.log(schaap);
for(let i=0;i<product.length;i++) {
if ( rowID != inputID) {
rowID++
//schaap.push({aantal: product[i].aantal});
console.log( "inputID " + inputID + " en de ROW ID " + rowID);
//console.log(schaap);
//index = product.findIndex(x => x.aantal[i] === elements[i]);
if (rowID = product[i].aantal) {
//index = product.findIndex(x => x.aantal === elements.input);
elements[i].value = product[i].aantal;
//console.log("index" + index);
}
}
}
}
Thats what I added. Here below this was the code of my original questions:
let myTable = document.querySelector('#table');
let rowID = 0;
let inputID = 0;
//Array met objecten erin {} staat voor een object
let product = [
{omschrijving:"Brood", waarde:1, aantal:3, total:0},
{omschrijving:"Brocolli", waarde:0.99, aantal:2, total:0},
{omschrijving:"Krentenbollen", waarde:1.20, aantal:4, total:0},
{omschrijving:"Noten", waarde:2.99, aantal:2, total:0}
]
///Update totals
for(let i=0;i<product.length;i++)
{
product[i].total = product[i].waarde*product[i].aantal;
}
const total = product.reduce((currentTotal, productCal) => {
return productCal.total + currentTotal
}, 0)
uitslag = total.toFixed(2);
document.getElementById('totaal').innerHTML = "Totaal bedrag " + uitslag;
////Table
let headers = ['Name', 'Prijs', 'Aantal', 'Totaal', 'Aanpassen'];
let table = document.createElement('table');
let headerRow = document.createElement('tr');
headers.forEach(headerText => {
let header = document.createElement('th');
let textNode = document.createTextNode(headerText);
header.appendChild(textNode);
headerRow.appendChild(header);
});
table.appendChild(headerRow);
///////////td is column
product.forEach(emp => {
let row = document.createElement('tr');
Object.values(emp).forEach(text => {
//console.log("row" + rowID);
let cell = document.createElement('td');
let textNode = document.createTextNode(text);
cell.appendChild(textNode);
row.appendChild(cell);
})
input = document.createElement('input');
cell = document.createElement('td');
input.type = 'number';
//input.value
input.addEventListener('click', eentjeMeer() );
cell.appendChild(input);
row.appendChild(cell);
/*
let input = document.createElement('input');
input.type = "step";
table.appendChild(input);
*/
table.appendChild(row);
});
myTable.appendChild(table);
/////////////////////
/////////////////INPUTS AANPASSEN MET WAARDE VAN ARRAY////////////////////////////
var elements = table.getElementsByTagName('input'); //misschien mot ik het in een array droppen
for(let j=0;j<elements.length;j++) {
inputID++;
//console.log("de input ID" + inputID);
//product.push({input: elements[j]});
//console.log(schaap);
for(let i=0;i<product.length;i++) {
if ( rowID != inputID) {
rowID++
//schaap.push({aantal: product[i].aantal});
console.log( "inputID " + inputID + " en de ROW ID " + rowID);
//console.log(schaap);
//index = product.findIndex(x => x.aantal[i] === elements[i]);
if (rowID = product[i].aantal) { //hier GAAT IETS GOED ALS laatst op 22:22 HIJ DOET DE LAATSTE NIET WHY???
//index = product.findIndex(x => x.aantal === elements.input);
elements[i].value = product[i].aantal;
//console.log("index" + index);
}
}
}
}
//product[i].total = product[i].waarde*product[i].aantal;
///////////////////////////////////////////////////
for(let j=0;j<product.length;j++) {
//let row = document.createElement('tr');
}
function updateTable() {
test = [];
b1 = document.getElementById('naam').value;
b2 = document.getElementById('prijs').value;
b3 = document.getElementById('qty').value;
test.push({omschrijving:b1, waarde:b2, aantal:b3, total:0});
for(let i=0;i<test.length;i++)
{
test[i].total = test[i].waarde*test[i].aantal;
}
test.forEach(emp => {
let row = document.createElement('tr');
Object.values(emp).forEach(text => {
let cell = document.createElement('td');
let textNode = document.createTextNode(text);
cell.appendChild(textNode);
row.appendChild(cell);
})
table.appendChild(row);
});
myTable.appendChild(table);
//console.log(product);
/////////////////////////totaal na update WORDT AFGEROND DOOR PARSEINT?!?!?!
const total0 = test.reduce((currentTotal, productCal) => {
return productCal.total + currentTotal
}, 0)
console.log("total0 = " + total0);
yo = total0.toFixed(2);
yo1 = Number.parseInt(yo) + Number.parseInt(uitslag);
document.getElementById('totaal').innerHTML = "Totaal bedrag " + yo1;
console.log(yo);
}
function eentjeMeer(){
var elements = table.getElementsByTagName('input'); //misschien mot ik het in een array droppen
for(let j=0;j<elements.length;j++) {
inputID++;
//console.log("de input ID" + inputID);
//product.push({input: elements[j]});
//console.log(schaap);
for(let i=0;i<product.length;i++) {
if ( rowID != inputID) {
rowID++
//schaap.push({aantal: product[i].aantal});
//console.log(schaap);
//index = product.findIndex(x => x.aantal[i] === elements[i]);
if (rowID = product[i].aantal) {
console.log(product[i].aantal); //het doet het wel nu....iets met inputID denk ik
objIndex = product.findIndex((obj => obj.aantal == rowID));
//product[i].aantal.name = elements[i].value;
testje = product[i].aantal;
//elements[i].value = inputID;
//inputID = product[i].aantal;
//product[i].aantal = elements[i].value;
//console.log(elements[i].value);
//console.log(product);
//console.log("index" + index);
}
}
}
}
};
body {
text-align: center;
}
div {
display: inline-block;
}
button {
display: inline-block;
padding: 10px 20px;
}
#table {
display: block;
margin-top: 20px;
}
th, td {
border: 1px solid black;
padding: 5px;
}
#totaal {
border: 2px solid black;
background-color: skyblue;
padding: 5px;
}
<!DOCTYPE html>
<head>
<link rel="stylesheet" href="style.css">
<title>Boodschappenlijst</title>
</head>
<body>
<h1> Boodschappenlijst </h1>
<div id="container"></div>
<div>
<div id="table"></div>
</div>
<p>Naam</p>
<input type="text" name="item" id="naam" /><br />
<p>Aantal</p>
<input type="text" name="quantity" id="qty" /><br />
<p>Prijs</p>
<input type="text" name="price" id="prijs" /><br/><br />
<input type="button" value="Add Product" onclick="updateTable()" id="add"><br /><br />
<div id="totaal"></div>
<script src="script.js"></script>
</body>
</html>
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>