Check input form need two click to be validated - javascript
I need to click two times on my button to validate my form,
I have a event listener like this :
btnCartSend.addEventListener('click', function(){
checkInput();
window.location="confirm.html "
})
Then it call
function checkInput(){
if (fristName.length == 0){
alert("test 1");
}else if(lastName.length == 0){
alert("test 2");
}else if(address.length == 0){
alert("test 3");
}else if(zip.length != 5){
alert("test 4");
}else if(city.length == 0){
alert("test 5");
}else if(email.length == 0){
alert("test 6");
}else {
console.log('send to api');
sendToApi();
}
}
I put the whole project on my github and here you have the cart file with both functions and others: https://github.com/lliolla/P5-onorico/blob/master/frontend/js/cart.js
I have cloned your project and find some omissions that you are using shoppingCart.length everywhere while shoppingCart is having null initially, so wherever you are using the length or any other property, please first check if that variable is null or not.
After fixing all this, I have run the code and it is validating the form with a single click.
Check your code or replace the cart.js with the below code I have corrected at some places.
//déclaration des variables
let shoppingCart = JSON.parse(localStorage.getItem('shoppingCart')); // recuperer le panier convertit en javascript
console.log('shoppingCart',shoppingCart)
let orderInfos = JSON.parse(localStorage.getItem('orderInfos')); // recuperer le retour API convertit en javascript
console.log('orderInfos',orderInfos)
let form =document.getElementById("form") // formulaire
let btnCartSend =document.getElementById("btnCartSend") // bouton envoi
let tableCartRows = document.getElementById("tableCartRows")// corps du tableau
let tableFoot = document.getElementById("tableFoot")//pied du tableau
let table=document.getElementById("table") // tableau entier
let tableTitle=document.getElementById("tableTitle") // h2
let orderModal = document.getElementById('orderModal')// modal de confirmation de commande
//variables info clients a vérifier
let fristName = document.getElementById("inputFristName").value;
let lastName= document.getElementById("inputLastName").value;
let address = document.getElementById("inputAddress").value;
let zip = document.getElementById("inputZip").value;
let city = document.getElementById("inputCity").value;
let email = document.getElementById("InputMail").value;
function showCart(){
//au chargement de la page génerer dynamiquement le panier si shoppingcart est plein sinon on affiche panier vide avec bouton de retour a teddiesHome.html
if (shoppingCart && shoppingCart.length <= 0) {
// on masque le cart le formulaire et son bouton et on affiche un retour à la page des produits
tableTitle.style.display = "none";
tableCart.style.display = "none";
form.style.display = "none";
btnCartSend.style.display = "none";
let h2 = document.createElement("h2");
table.appendChild(h2);
h2.textContent ="Votre panier est vide ";
let p = document.createElement("p");
table.appendChild(p);
p.textContent ="Faites un petit tour dans nos boutiques et laissez-vous tenter";
var a = document.createElement("a");
p.appendChild(a);
a.setAttribute('class','btn btn-secondary btn-lg btn-block');
a.setAttribute('href','teddiesHome.html');
a.setAttribute('role','button');
a.textContent = "Continuer mes achats";
}else{
totalCartPrice ();// total price du panier
//verifier si il y a des doublons
if(shoppingCart) {
createTableCart(); //sinon afficher le panie
}
}
}
showCart()
function delateItemCart(index){
//supprimer un teddy en fonction de son index dans teddyArray
console.log ("suprimer le teddy dans shopping cart",index, shoppingCart[index])
shoppingCart.splice(index,1)
console.log ("suprimer le teddy dans shopping cart", shoppingCart)
//vide le localstorage
localStorage.clear();
//mettre à jour le local storage avec nouveau panier
localStorage.setItem('shoppingCart',JSON.stringify(shoppingCart) ) ;
totalCartPrice ();
// recharger la page
document.location.reload();
//}
}
// on fait une boucle pour acceder à tous les boutons supprimer
let bntDelated = document.querySelectorAll('.bntDelated') //boutons supprimer
for (i=0 ;i<bntDelated.length ; i++ ){
console.log("bntDelated", bntDelated[i])
bntDelated[i].addEventListener("click", function(){ // au clic sur sup on suprimer le teddy coorepondant dans le shopping cart
let index = Array.from(bntDelated).indexOf(event.target) ;
console.log("click pour suprimer envoi l'index, ",index)
delateItemCart(index);
})
}
// au clic sur le btn envoyer la commande
btnCartSend.addEventListener('click', function(){
checkInput();// on verifie le format des input
sendToApi(); // on envoi les donnees a l'api et on recuperer le num de commande
//si tout est ok on affiche le modal avec un num de commande et le prix total
window.location="confirm.html "
})
function totalCartPrice (){
if(shoppingCart) {
let totalCart = 0;
for ( let i=0; i<shoppingCart.length ; i++ ){
let cartQte = shoppingCart[i].qte;
let cartprice = shoppingCart[i].price;
totalCart += cartQte * cartprice
localStorage.setItem('totalCart',JSON.stringify(totalCart) );
}
}
}
function createTableCart(){// on affiche dynamiquement le panier sous forme de tableau
// on boucle le shopping cart pour afficher une ligne par teddy
for ( let i=0; i<shoppingCart.length ; i++ ){
let tr1 = document.createElement("tr");
tableCartRows.appendChild(tr1);
let th7 = document.createElement("th");
tr1.appendChild(th7);
th7.setAttribute('scoop','row');
th7.textContent="counter ligne";
let td = document.createElement("td");
tr1.appendChild(td);
let teddyname =shoppingCart[i].name ;
td.textContent= teddyname;
td.setAttribute("id","Name")
let td1 = document.createElement("td");
tr1.appendChild(td1);
let teddyColor = shoppingCart[i].colors;
td1.textContent=teddyColor;
td.setAttribute("id","Color")
let price = shoppingCart[i].price + "€";
let td2 = document.createElement("td");
tr1.appendChild(td2);
td2.textContent=price;
let td3 = document.createElement("td");
tr1.appendChild(td3);
td3.setAttribute("class","counter");
let div = document.createElement("div");
td3.appendChild(div);
div.setAttribute("class","number");
div.setAttribute("id","number");
div.textContent=shoppingCart[i].qte;
// let div1 = document.createElement("div")
// td3.appendChild(div1)
// div1.setAttribute("class","counter-clic")
// let i1 = document.createElement("i")
// div1.appendChild(i1)
// i1.setAttribute("class","fas fa-plus plus")
// let i2 = document.createElement("i")
// div1.appendChild(i2)
// i2.setAttribute("class","fas fa-minus minus")
// let td4 = document.createElement("td")
// tr1.appendChild(td4)
// td4.textContent= subTotal
let td5 = document.createElement("td");
tr1.appendChild(td5);
td5.setAttribute("class","text-center");
let i3 = document.createElement("i");
td5.appendChild(i3);
i3.setAttribute("class","fas fa-times-circle bntDelated");
}
let tr2 = document.createElement("tr");
tableFoot.appendChild(tr2);
let td6 = document.createElement("td");
tr2.appendChild(td6);
td6.setAttribute("colspan","2");
let td7 = document.createElement("td");
tr2.appendChild(td7);
td7.textContent = "Total"
let totalCart = localStorage.getItem('totalCart')
let td8 = document.createElement("td");
tr2.appendChild(td8);
td8.setAttribute("colspan","3");
td8.setAttribute('class','text-right');
td8.textContent = totalCart + "€";
}
function checkInput(){
if (fristName.length == 0){
alert("test 1");
}else if(lastName.length == 0){
alert("test 2");
}else if(address.length == 0){
alert("test 3");
}else if(zip.length != 5){
alert("test 4");
}else if(city.length == 0){
alert("test 5");
}else if(email.length == 0){
alert("test 6");
}else {
console.log('send to api');
sendToApi();
}
}
function sendToApi(){
// crerer un objet qui va recuperer la value de chaque input du formulaire
//creation de la class client
class customer{
constructor(fristName,lastName,address,city,email){
this.lastName = lastName;
this.fristName = fristName;
this.address = address;
this.city = city;
this.email = email;
}
}
// objet contenant les infos du formulaire
let newCustumer = new customer (lastName,fristName, address,city,email)
// creer un tableau pour envoyer uniquement les ID des teddy
//recupérer le shoppingCart
let apiCart =JSON.parse(localStorage.getItem("shoppingCart")) ;
console.log("apiCart",apiCart)
let apiCartArray = []; // tableau des id des teddy
//parcourir le tableau et recuperer les id des teddy
if(apiCart) {
for (let i=0; i<apiCart.length; i++){
apiCartArray.push(apiCart[i].id)
console.log("send api id",apiCartArray)
}
}
// POST API
fetch("http://localhost:3000/api/teddies/order", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
contact: {
firstName: newCustumer.fristName,
lastName: newCustumer.lastName,
address: newCustumer.address,
city: newCustumer.city,
email: newCustumer.email,
},
products: apiCartArray,
}),
})
.then((response) => {
if (response.ok) {
return response.json();
}
})
.then((data) => {
localStorage.setItem("orderInfos", JSON.stringify(data));
})
.catch((error) => console.log("erreur de type : ", error));
}
Related
I need to create a function that before adding an item to the first table the function must check if the second table does not contain the same item
I'm trying to check the items in the first table with the items in the second table before adding the items in the first table. I already have another function that adds the items, but before adding I need another function that can check before being added to not have repeated items const fruits = ['Banane', 'Fraise', 'Melon', 'Orange']; const panier2 = ['Limon', 'Clementine', 'Kiwi', 'Melon', 'Coco']; function verifiePanier(a, b) { for (i = 0; i < 0; i++) { if (a[i] == b[i]) { console.log('Cette element ' + b + 'il y a deja dans le panier:') } else { console.log('Vous avez ajouter toutes les élements') } } return } console.log(verifiePanier(fruits, panier2)) All my code // On va ici créer un programme pour gérer un panier de courses, qui contiendra essentiellement des fruit //****** */ Créer une fonction pour ajoter un élement au panier let panier = []; const fruits = ['Banane', 'Fraise', 'Melon', 'Orange']; function ajouterElement(element) { for (i = 0; i < element.length; i++) { panier.push(element[i]); } return panier } //console.table(ajouterElement(fruits)); // ****** Créer une fonction pour vider le panier function videurElement(element) { for (i = fruits.length; i > 0; i--) { fruits.pop(element[i]); } return fruits } // console.table(videurElement(fruits)); //***** Créer une fonction pour recherche un élement dans le panier function findElement(element) { let recherche = ''; recherche = fruits.indexOf(element) return recherche } // console.log(findElement('Morango')); //****** Ne pas oublier de tester le programme //****** Bonus: créer une fonction pour ajouter un tableau d'élement à notre panier const panier2 = ['Limon', 'Clementine', 'Kiwi', 'Melon', 'Coco']; function ajoutertable(ajouter, element) { panier = ajouter.concat(element) return panier } //console.table(ajoutertable(fruits, panier2));
Like this: function inArray(element, array){ return array.includes(element); } the short version: const inArray= (element, array) => array.includes(element) note that you need to declare the short version before you use it. the function will return a boolean when the item is found in the array. the rest of your code will be something like this: if(!inArray(element, array)){ addToArray(element) } or when the array is hard coded (not reccomended): if(!array.includes(element)){ addToArray(element) }
How to use "required" attribute in a form, when we use e.preventDefault()?
I need to make a form in html5, no problem. But this form needs the e.preventDefault on the submit button, to add some links on a new page. And the inputs in the form must have the "required" attribute. So my problem is, when I don't use e.preventDefault, "required" works, but my new link doesn't appears on my page. If I use e.preventDefault on submit button, my new links appears with the others, but the problem is "required" doesn't work on the inputs, when I submit the form... Thank you Here is my code : /* Activité 1 */ // Liste des liens Web à afficher. Un lien est défini par : // - son titre // - son URL // - son auteur (la personne qui l'a publié) var listeLiens = [ { titre: "So Foot", url: "http://sofoot.com", auteur: "yann.usaille" }, { titre: "Guide d'autodéfense numérique", url: "http://guide.boum.org", auteur: "paulochon" }, { titre: "L'encyclopédie en ligne Wikipedia", url: "http://Wikipedia.org", auteur: "annie.zette" } ]; var zoneLiensElt = document.createElement("div"); zoneLiensElt.id = "zoneliens"; var contenuElt = document.getElementById("contenu"); contenuElt.appendChild(zoneLiensElt); function afficherLiens() { listeLiens.forEach(function (lien) { // Définition des variables du DOM var divElt = document.createElement("div"); var lienElt = document.createElement("a"); var brElt = document.createElement("br"); var spanElt = document.createElement("span"); var urlElt = document.createTextNode(" " + lien.url); var auteurElt = document.createTextNode("Ajouté par " + lien.auteur); var espaceLiensElt = document.createElement("div"); espaceLiensElt.id = "liens"; // Définition des liens lienElt.href = lien.url; lienElt.style.color = "#428bca"; lienElt.textContent = lien.titre; lienElt.style.fontWeight = "bold"; lienElt.style.textDecoration = "none"; divElt.classList.add("lien"); // Intégration des éléments divElt.appendChild(lienElt); spanElt.appendChild(urlElt); spanElt.appendChild(brElt); spanElt.appendChild(auteurElt); divElt.appendChild(spanElt); espaceLiensElt.appendChild(divElt); zoneLiensElt.appendChild(espaceLiensElt); }); } afficherLiens(); // Création du bloc contenant le bouton et le formulaire contenuElt.insertAdjacentHTML("afterbegin", '<div id="zoneform"></div>'); var boutonElt = document.createElement("button"); boutonElt.textContent = "Ajouter un lien"; var zoneFormElt = document.getElementById("zoneform"); zoneFormElt.id = "zoneform"; zoneFormElt.appendChild(boutonElt); zoneFormElt.style.marginBottom = "20px"; // Création du formulaire et des variables du DOM var formElt = document.createElement("form"); var auteurElt = document.createElement("input"); var titreElt = document.createElement("input"); var urlElt = document.createElement("input"); var ajouterElt = document.createElement("input"); var labelAuteurElt = document.createElement("label"); var labelTitreElt = document.createElement("label"); var labelUrlElt = document.createElement("label"); // Création du champ auteur labelAuteurElt.setAttribute("for", "auteur"); auteurElt.id = "auteur"; auteurElt.name = "auteur"; auteurElt.type = "text"; auteurElt.setAttribute("placeholder", "Entrez votre nom"); auteurElt.setAttribute("required", "required"); auteurElt.style.width = "300px"; auteurElt.style.margin = "10px"; // Création du champ titre labelTitreElt.setAttribute("for", "titre"); titreElt.id = "titre"; titreElt.name = "titre"; titreElt.type = "text"; titreElt.setAttribute("placeholder", "Entrez le titre du lien"); titreElt.setAttribute("required", "required"); titreElt.style.width = "300px"; titreElt.style.margin = "10px"; // Création du champ url labelUrlElt.setAttribute("for", "url"); urlElt.id = "url"; urlElt.name = "url"; urlElt.type = "text"; urlElt.setAttribute("placeholder", "Entrez l'URL du lien"); urlElt.setAttribute("required", "required"); urlElt.style.width = "300px"; urlElt.style.margin = "10px"; // Création du bouton ajouter ajouterElt.type = "submit"; ajouterElt.id = "ajouter"; ajouterElt.value = "Ajouter un lien"; ajouterElt.style.margin = "10px"; // Ajout des champs dans le formulaire formElt.appendChild(labelAuteurElt); formElt.appendChild(auteurElt); formElt.appendChild(labelTitreElt); formElt.appendChild(titreElt); formElt.appendChild(labelUrlElt); formElt.appendChild(urlElt); formElt.appendChild(ajouterElt); // Affichage du formulaire boutonElt.addEventListener("click", function() { zoneFormElt.innerHTML = ""; zoneFormElt.appendChild(formElt); }); // Actions du bouton submit ajouterElt.addEventListener("click", function(e) { var nouveauLien = { titre: titreElt.value, url: urlElt.value, auteur: auteurElt.value }; listeLiens.unshift(nouveauLien); zoneLiensElt.innerHTML = ""; afficherLiens(); e.preventDefault(); }); body { font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; background-color: #eee; margin-left: 30px; margin-right: 30px; } span { font-weight: normal; font-size: 80%; } .lien { background: white; padding: 10px; margin-bottom: 10px; } <!doctype html> <html> <head> <meta charset="utf-8"> <link rel="stylesheet" href="../css/liensweb.css"> <title>Activité 2</title> </head> <body> <h1>Activité 2</h1> <!-- Les nouveaux éléments sont ajoutés dans cette balise --> <div id="contenu"> </div> <script src="../js/liensweb.js"></script> </body> </html>
This is pretty much a duplicate of: How to force a html5 form validation without submitting it via jQuery You'll find documentation there: https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Forms/Data_form_validation http://www.w3schools.com/js/js_validation_api.asp
Parse a SRT file with jQuery Javascript
I'm trying to parse .srt but I get an internal error and I can't figure out what is it. Here is my code: var subtitles; jQuery.get('SB_LKRG-eng.srt', function(data) { //alert(data); function strip(s) { return s.replace(/^\s+|\s+$/g,""); } srt = data.replace(/\r\n|\r|\n/g, '\n'); //alert(srt); srt = strip(srt); //alert(srt); var srt_ = srt.split('\n\n'); alert(srt_); var cont = 0; for(s in srt_) { st = srt_[s].split('\n'); alert(st); if(st.length >=2) { n = st[0]; i = strip(st[1].split(' --> ')[0]); o = strip(st[1].split(' --> ')[1]); t = st[2]; if(st.length > 2) { for(j=3; j<st.length;j++) t += '\n'+st[j]; } subtitles[cont].number = n; subtitles[cont].start = i; subtitles[cont].end = o; subtitles[cont].text = t; //alert(subtitles[cont].start); } cont++; } }); I can extract the first 4 subtitles and then the code stops and breaks exception: TypeError, I can't understand why... Here a sample of the subtitles file: 1 00:00:01,000 --> 00:00:04,000 Descargados de www.AllSubs.org 2 00:00:49,581 --> 00:00:52,049 Bueno, tienes que escapar, tengo que ir a jugar 3 00:00:52,084 --> 00:00:55,178 Tengo que encontrar un día que está lleno de nada más que sol 4 00:00:55,220 --> 00:00:57,552 Crucero por la calle, moviéndose al compás 5 00:00:57,589 --> 00:01:00,683 Todos los que conoces está teniendo nada más que diversión 6 00:01:00,726 --> 00:01:03,251 Deja todo detrás de ti 7 00:01:03,295 --> 00:01:06,128 Siente esas palmeras soplan 8 00:01:06,165 --> 00:01:09,157 La gente en el norte no puede encontrar 9 00:01:09,201 --> 00:01:11,829 Están fuera de palear la nieve 10 00:01:11,870 --> 00:01:14,998 El tiempo para moverse, pero no seas lento 11 00:01:15,040 --> 00:01:17,941 En sus marcas, prepárate para ir Part of the code is from: http://v2v.cc/~j/jquery.srt/jquery.srt.js Can anyone help me? Thank you
var PF_SRT = function() { //SRT format var pattern = /(\d+)\n([\d:,]+)\s+-{2}\>\s+([\d:,]+)\n([\s\S]*?(?=\n{2}|$))/gm; var _regExp; var init = function() { _regExp = new RegExp(pattern); }; var parse = function(f) { if (typeof(f) != "string") throw "Sorry, Parser accept string only."; var result = []; if (f == null) return _subtitles; f = f.replace(/\r\n|\r|\n/g, '\n') while ((matches = pattern.exec(f)) != null) { result.push(toLineObj(matches)); } return result; } var toLineObj = function(group) { return { line: group[1], startTime: group[2], endTime: group[3], text: group[4] }; } init(); return { parse: parse } }(); jQuery.get('demo.srt') .done(function(text) { try { //Array with {line, startTime, endTime, text} var result = PF_SRT.parse(text); } catch (e) { //handle parsing error } }); Demo https://jsfiddle.net/5v7wz4bq/
Here is one problem: o = strip(st[1].split(' --> ')[1]); At this line, when there isn't any ' --> ' to split, the returned length of the array is 1, which errors when you ask for array item 2. And here is another: subtitles[cont].number = n; .... Neither is the subtitles declared, nor its properties .number, ... etc. Update Here is a sample that works (switched the jQuery "read srt file" part for the data) var data = document.getElementById("data").innerHTML; data = data.replace(/>/g,">"); function strip(s) { return s.replace(/^\s+|\s+$/g,""); } srt = data.replace(/\r\n|\r|\n/g, '\n'); srt = strip(srt); var srt_ = srt.split('\n\n'); var cont = 0; var subtitles = []; for(s in srt_) { st = srt_[s].split('\n'); if(st.length >=2) { var st2 = st[1].split(' --> '); var t = st[2]; if(st.length > 2) { for(j=3; j < st.length;j++) t += '\n'+st[j]; } subtitles[cont] = { number : st[0], start : st2[0], end : st2[1], text : t } console.log(subtitles[cont].number + ": " + subtitles[cont].text); document.body.innerHTML += subtitles[cont].number + ": " + subtitles[cont].text + "<br>"; cont++; } } <div id="data" style="display:none">1 00:00:01,000 --> 00:00:04,000 Descargados de www.AllSubs.org 2 00:00:49,581 --> 00:00:52,049 Bueno, tienes que escapar, tengo que ir a jugar 3 00:00:52,084 --> 00:00:55,178 Tengo que encontrar un día que está lleno de nada más que sol 4 00:00:55,220 --> 00:00:57,552 Crucero por la calle, moviéndose al compás 5 00:00:57,589 --> 00:01:00,683 Todos los que conoces está teniendo nada más que diversión 6 00:01:00,726 --> 00:01:03,251 Deja todo detrás de ti 7 00:01:03,295 --> 00:01:06,128 Siente esas palmeras soplan 8 00:01:06,165 --> 00:01:09,157 La gente en el norte no puede encontrar 9 00:01:09,201 --> 00:01:11,829 Están fuera de palear la nieve 10 00:01:11,870 --> 00:01:14,998 El tiempo para moverse, pero no seas lento 11 00:01:15,040 --> 00:01:17,941 En sus marcas, prepárate para ir </div>
It is better to use the following regex to cover them if the number of lines of text in each section increases /(\d+)\n([\d:,]+)\s+-{2}\>\s+([\d:,]+)\n([\s\S]*?(?=\n{2}|$))/g View the output on the console let subtitle = document.getElementById('subtitle').value; console.log(_subtitle(subtitle)); function _subtitle(text) { let Subtitle = text; let Pattern = /(\d+)\n([\d:,]+)\s+-{2}\>\s+([\d:,]+)\n([\s\S]*?(?=\n{2}|$))/g; let _regExp = new RegExp(Pattern); let result = []; if (typeof (text) != "string") throw "Sorry, Parser accept string only."; if (Subtitle === null) return Subtitle; let Parse = Subtitle.replace(/\r\n|\r|\n/g, '\n'); let Matches; while ((Matches = Pattern.exec(Parse)) != null) { result.push({ Line: Matches[1], Start: Matches[2], End: Matches[3], Text: Matches[4], }) } return result; } <textarea id="subtitle">1 00:00:00,000 --> 00:00:00,600 Hi my friends 2 00:00:00,610 --> 00:00:01,050 In the first line, everything works properly But there is a problem in the second line that I could not solve :( 3 00:00:01,080 --> 00:00:03,080 But then everything is in order and good 4 00:00:03,280 --> 00:00:05,280 You do me a great favor by helping me. Thankful</textarea>
Node.js, Mongoose function return an error the first time but not the second
I have a function which return some elements from my MongoDB database but I have a problem with my variables. It says that one of my variable isn't defined the first time but then if I refresh, the error disappear. So I think it's an error of global variable defined in an inner scope which can't be accessed the first time or something like that. So here's my code : exports.findQuestion = function findQuestion() { var tabRand = new Array(); // on déclare un nouveau tableau où on va stocker les jets de rand var query = boardModel.find(null); // on cherche toutes les entrées dans la collection query.exec(function (err, tabQuestion) { if (err) { throw err;} var rep = tabQuestion[0]; var rand = Math.floor((Math.random()*rep.question.length+1)); // random sur le tableau var i = false; tabRand[0] = 0; while (i == false) { for(var random in tabRand) // on vérifie le résultat du rand avec les rand précédents { if(random != rand) // si le rand est différent on le garde { i = true; if(tabRand.length-1 == rep.question.length) // si la taille de tabRand est égale à la longueur du tableau de questions de la collection alors on le reinitialise { tabRand = new Array(); } } } tabRand.push[rand]; // on ajoute le rand précédent à tabRand rand = Math.floor((Math.random()*rep.question.length+1)); // et on en fait un nouveau } quest = rep.question[rand-1].quest; // on récupère le resultat attendu repJuste = rep.question[rand-1].rep_j; repFausse1 = rep.question[rand-1].rep_f1; repFausse2 = rep.question[rand-1].rep_f2; gainQ = rep.question[rand-1].gain; nomTr = rep.question[rand-1].name_t; }); return [quest, repJuste, repFausse1, repFausse2, gainQ, nomTr]; } So the first time, it says that quest is not defined but then everything works well ... PS : Sorry for the half-French, half-English code ^^
I see one problem here, you can't return something in a asynchronous function, you should use a callback. If you want to understand it : You do your asynchronous query (and you do something in your callback with the result tabQuestion) and your return something but you're not sure your async function is done. try async.js to help you manage your asynchronous problems EDIT: async.parallel([ function(callback){ boardModel.find().exec(function (err, tabQuestion) { if (err) { throw err;} var rep = tabQuestion[0]; var rand = Math.floor((Math.random()*rep.question.length+1)); // random sur le tableau var i = false; tabRand[0] = 0; while (i == false) { for(var random in tabRand) // on vérifie le résultat du rand avec les rand précédents { if(random != rand) // si le rand est différent on le garde { i = true; if(tabRand.length-1 == rep.question.length) // si la taille de tabRand est égale à la longueur du tableau de questions de la collection alors on le reinitialise { tabRand = new Array(); } } } tabRand.push[rand]; // on ajoute le rand précédent à tabRand rand = Math.floor((Math.random()*rep.question.length+1)); // et on en fait un nouveau } quest = rep.question[rand-1].quest; // on récupère le resultat attendu repJuste = rep.question[rand-1].rep_j; repFausse1 = rep.question[rand-1].rep_f1; repFausse2 = rep.question[rand-1].rep_f2; gainQ = rep.question[rand-1].gain; nomTr = rep.question[rand-1].name_t; }); callback(null, quest, repJuste, repFausse1, repFausse2, gainQ, nomTr); }], function(err){ if(err){ console.log(err); }else{ console.timeEnd('chargement bd'); socket.emit('event', {'quest': quest, 'repJuste' : repJuste }); //add all your params } });
Programming a loop in JavaScript
I want to create a script that when I write a string to check if this string is a number or no if it isn't a number it should give me the input dialogue again, the is the code I tried: <script> var nombre; nombre = parseInt(prompt("Donnez un nombre entre 0 et 999: ")); var nombreIsInt = false; while(!nombreIsInt) { if(isNaN(nombre)) prompt("Svp Saisie un nombre entre 0 et 999: "); else nombreIsInt = true; } </script> The problem is that when I write a number it gives me the input dialogue again.
Try a do-while loop: do { var nombre = parseInt(prompt("Donnez un nombre entre 0 et 999: ")); var nombreIsInt = !isNaN(nombre); } while (!nombreIsInt);
You need to assign the prompt to nombre. Here: <script> var nombre; nombre = parseInt(prompt("Donnez un nombre entre 0 et 999: ")); var nombreIsInt = false; while(!nombreIsInt) { if(isNaN(nombre)) nombre = prompt("Svp Saisie un nombre entre 0 et 999: "); // the problem is here else nombreIsInt = true; } </script>