Javascript quiz where a question is appearing inappropriately - javascript

I split a 6-question form to show one question at a time, ie it turned into a quiz. The problem is the quiz is working perfectly with 5 questions, but not 6. I don't know why question 6 is appearing together with all other questions, as in the following image:
https://i.imgur.com/j3n0I8b.png
If I delete question 6, the error disappears, that is, question 5 does not appear with all other questions, and the program goes back to displaying only one question at a time.
The logic of showing/hiding questions is in (1), in function nextQuestion() and in the events submit#.addEventListener(). Most likely the problem is here. But, it doesn't make sense to me that nextQuestion() works until #question-5, but not for #question-6.
All my buttons are type="button", except for the last question, which is type="submit". This had given me problems before.
Thanks to anyone who suggests another logic and change the code completely, however, my interest is to know why this code is not working.
EDITED AFTER ANSWERS: Here's the code working for anyone who might be interested:
// Variables
var submit1 = document.getElementById('submit1');
var submit2 = document.getElementById('submit2');
var submit3 = document.getElementById('submit3');
var submit4 = document.getElementById('submit4');
var submit5 = document.getElementById('submit5');
var previous2 = document.getElementById('previous2');
var previous3 = document.getElementById('previous3');
var previous4 = document.getElementById('previous4');
var previous5 = document.getElementById('previous5');
var previous6 = document.getElementById('previous6');
// Next question button
submit1.addEventListener('click', function() {
nextQuestion(2);
growProgressBar('33.33%');
})
submit2.addEventListener('click', function() {
nextQuestion(3);
growProgressBar('50%');
})
submit3.addEventListener('click', function() {
nextQuestion(4);
growProgressBar('66.67%');
})
submit4.addEventListener('click', function() {
nextQuestion(5);
growProgressBar('83.33%');
})
submit5.addEventListener('click', function() {
nextQuestion(6);
growProgressBar('100%');
})
// grow Progress Bar
function growProgressBar(percentage_width) {
var bar = document.getElementById('progress_bar');
bar.style.width = percentage_width;
}
// Shows next question, hides current
function nextQuestion(question_number) {
/*
question_number é a próxima questão, aquela que clicamos o botão para ir
exemplo, se estamos na questão 1
current_question_number = 2 - 1 = 1
question_number = 2
se estamos na questão 2
current_question_number = 3 - 1 = 1
question_number = 3
*/
var current_question_number = question_number - 1; //question_number é a próxima questão
var question_number = question_number.toString(); //transforma em string para poder ser lido no getElementById
var current_question_number = current_question_number.toString(); //transforma em string para poder ser lido no getElementById
document.getElementById('question-' + question_number).style.display = 'block';
document.getElementById('question-' + current_question_number).style.display = 'none';
}
// Previous question button
previous2.addEventListener('click', function() {
previousQuestion(1);
shrinkProgressBar('16.67%');
})
previous3.addEventListener('click', function() {
previousQuestion(2);
shrinkProgressBar('33%');
})
previous4.addEventListener('click', function() {
previousQuestion(3);
shrinkProgressBar('50%');
})
previous5.addEventListener('click', function() {
previousQuestion(4);
shrinkProgressBar('66.67%');
})
previous6.addEventListener('click', function() {
previousQuestion(5);
shrinkProgressBar('83.33%');
})
// Shrink Progress Bar
function shrinkProgressBar(percentage_width) {
var bar = document.getElementById('progress_bar');
bar.style.width = percentage_width;
}
// Shows previous question, hides current
function previousQuestion(question_number) {
var current_question_number = question_number + 1;
var question_number = question_number.toString();
var current_question_number = current_question_number.toString();
var el = document.getElementById('question-' + question_number);
var el2 = document.getElementById('question-' + current_question_number);
el.style.display = 'block';
el2.style.display = 'none';
}
#question-2,
#question-3,
#question-4,
#question-5,
#question-6 {
display: none;
}
#progress_bar {
background-color: #018fd0;
width: 16.67%;
height: 10px;
transition: all 100ms ease-in-out;
}
<form class="questions_box formulario" action="enviar-landing-page-rsa.php" method="post">
<div id="question-1">
<h3>Qual o nome do seu filho(a)?</h3>
<div class="input-formulario">
<i class="far fa-user"></i>
<input required type="text" name="nome_crianca_rsa" id="nome_crianca_rsa" placeholder="Digite o nome do(a) aluno(a)" oninput="checkStudentsName()">
<span id="error-nome-crianca-rsa"></span>
</div>
<div class="text-center mt-3">
<input type="button" id="submit1" class="btn btn-warning btn-lg" value="Enviar Resposta" style="display: none;" />
</div>
</div>
<div id="question-2">
<h3>Qual a data de nascimento do seu filho(a)?</h3>
<div class="input-formulario">
<i class="far fa-calendar-alt"></i>
<input required type="text" name="data_nascimento_crianca_rsa" id="data_nascimento_crianca_rsa" placeholder="Digite a data de nascimento do(a) aluno(a)" oninput="checkNumber()" maxlength="2" />
<!-- se ao invés de onkeypress, colocar onkeyup, vai aceitar preenchimento de caracteres que não números -->
</div>
<div class="text-center mt-3">
<input type="button" id="submit2" class="btn btn-warning btn-lg" value="Enviar Resposta" style="display: none;" />
</div>
<div class="text-end mt-3">
<input type="button" id="previous2" class="btn btn-danger btn-lg" value="Pergunta Anterior" style="display: block;" />
</div>
</div>
<div id="question-3">
<h3>Complete a frase com aquilo que lhe é mais importante: "Eu quero que meu filho ..."</h3>
<input type="radio" class="radioButton" name="objetivo" id="question-3-answer-a" value=1 required> Aproveite melhor o tempo que passa no computador ou celular.<br>
<input type="radio" class="radioButton" name="objetivo" id="question-3-answer-b" value=2> Melhore as notas de uma ou mais matérias na escola.<br>
<input type="radio" class="radioButton" name="objetivo" id="question-3-answer-c" value=3> Aumente sua criatividade.<br>
<input type="radio" class="radioButton" name="objetivo" id="question-3-answer-d" value=4> Dê os primeiros passos para se tornar um brilhante engenheiro no futuro.<br>
<div class="text-end mt-3">
<input type="button" id="submit3" class="btn btn-warning btn-lg" value="Enviar Resposta" style="display: none;" />
</div>
<div class="text-end mt-3">
<input type="button" id="previous3" class="btn btn-danger btn-lg" value="Pergunta Anterior" style="display: block;" />
</div>
</div>
<div id="question-4">
<h3>Qual o nome do(a) responsável?</h3>
<div class="input-formulario">
<i class="far fa-user"></i>
<input required type="text" name="nome_responsavel_rsa" id="nome_responsavel_rsa" placeholder="Digite seu nome" oninput="checkFathersName()">
<span id="error-nome-responsavel-rsa"></span>
</div>
<div class="text-center mt-3">
<input type="button" id="submit4" class="btn btn-warning btn-lg" value="Enviar Resposta" style="display: none;" />
</div>
<div class="text-center mt-3">
<input type="button" id="previous4" class="btn btn-danger btn-lg" value="Pergunta Anterior" style="display: block;" />
</div>
</div>
<div id="question-5">
<h3>Qual seu whatsapp?</h3>
<div class="input-formulario">
<i class="fab fa-whatsapp"></i>
<input required type="text" name="celular_rsa" id="celular_rsa" placeholder="Digite seu celular" maxlength="10" onkeypress="return maskMobile(event)" oninput="checkMobile()">
<span id="error-celular-rsa"></span>
</div>
<div class="text-end mt-3">
<input type="button" id="submit5" class="btn btn-warning btn-lg" value="Enviar Resposta" style="display: none;" />
</div>
<div class="text-end mt-3">
<input type="button" id="previous5" class="btn btn-danger btn-lg" value="Pergunta Anterior" style="display: block;" />
</div>
</div>
<div id="question-6">
<h3>Qual seu telefone residencial?*</h3>
<h6>*Para caso não consigamos contato no celular.</h6>
<div class="input-formulario">
<i class="fab fa-whatsapp"></i>
<input required type="text" name="telefone_rsa" id="telefone_rsa" placeholder="Digite seu telefone residencial" maxlength="9" oninput="checkTelephone()">
<span id="error-telefone-rsa"></span>
</div>
<div class="text-end mt-3">
<input type="submit" id="submit6" class="btn btn-warning btn-lg" value="Enviar Resposta" style="display: none;" />
</div>
<div class="text-end mt-3">
<input type="button" id="previous6" class="btn btn-danger btn-lg" value="Pergunta Anterior" style="display: block;" />
</div>
</div>
</form>
<script type="text/javascript">
function checkStudentsName() {
var countName = document.getElementById('nome_crianca_rsa');
var errorName = document.getElementById('error-nome-crianca-rsa')
countName.value = countName.value.replace(/[0-9]/g, ''); // Remove numbers
if (countName.value.length < 3) { // 0 chars entered
errorName.innerHTML = "O nome precisa ter ao menos 3 caracteres."
document.getElementById('submit1').style.display = 'none';
} else {
errorName.innerHTML = "";
document.getElementById('submit1').style.display = 'block';
}
}
function checkNumber() {
var countAge = document.getElementById('data_nascimento_crianca_rsa');
countAge.value = countAge.value.replace(/\D/, ''); // Remove caracteres que não sejam números
if (countAge.value.length == 0) { // 0 caracteres digitados
document.getElementById('submit2').style.display = 'none';
} else {
document.getElementById('submit2').style.display = 'block';
}
}
document.querySelectorAll('.radioButton').forEach(item => {
item.addEventListener('click', event => {
checkObjective();
})
})
function checkObjective() {
if (document.getElementsByName('objetivo').value == '') {
document.getElementById('submit3').style.display = 'none';
} else {
document.getElementById('submit3').style.display = 'block';
}
}
function checkFathersName() {
var countName = document.getElementById('nome_responsavel_rsa');
var errorName = document.getElementById('error-nome-responsavel-rsa')
countName.value = countName.value.replace(/[0-9]/g, ''); // Remove numbers
if (countName.value.length < 3) { // 0 chars entered
errorName.innerHTML = "O nome precisa ter ao menos 3 caracteres."
document.getElementById('submit4').style.display = 'none';
} else {
errorName.innerHTML = "";
document.getElementById('submit4').style.display = 'block';
}
}
function checkMobile() {
var countMobile = document.getElementById('celular_rsa');
var errorMobile = document.getElementById('error-celular-rsa');
if (countMobile.value.length < 8) {
errorMobile.innerHTML = "O celular precisa ter ao menos 8 dígitos";
document.getElementById('submit5').style.display = 'none';
} else {
errorMobile.innerHTML = "";
document.getElementById('submit5').style.display = 'block';
}
}
function maskMobile(evt) {
var tecla = evt.keyCode;
if (tecla >= 48 && tecla <= 57) {
var tel = document.getElementById("celular_rsa");
var tam = tel.value.length;
if (tecla != 8) { // 8 = espaço (em hexadecimal)
switch (tam) {
case 0:
tel.value = "(" + tel.value;
break;
case 3:
tel.value = tel.value + ")";
break;
case 9:
tel.value = tel.value + "-";
break;
}
}
} else {
return false;
}
}
function checkTelephone() {
var countMobile = document.getElementById('telefone_rsa');
var errorMobile = document.getElementById('error-telefone-rsa');
if (countMobile.value.length < 8) {
errorMobile.innerHTML = "O telefone precisa ter ao menos 8 dígitos";
document.getElementById('submit6').style.display = 'none';
} else {
errorMobile.innerHTML = "";
document.getElementById('submit6').style.display = 'block';
}
}
</script>

Related

Modal closed immediatly after form submit

I'm back with my form ....
My form validation runs well so now I try to load a confirmation modal after that my form was valided and submited, so that users just click "understood".
When I click on the submit button, my modal appear and disapear immediately, I think it's because, after that the form was submited, the window is refreshed.
I spend a whole day at this f**king things and I don't be able to fix it.
I don't understand something...
My question is simple, how can I load my modal after that my form was submited ??
My JS code :
function editNav() {
var x = document.getElementById("myTopnav");
if (x.className === "topnav") {
x.className += " responsive";
} else {
x.className = "topnav";
}
}
// DOM Elements
const modalbg = document.querySelector(".bground");
const modalBtn = document.querySelectorAll(".modal-btn");
const formData = document.querySelectorAll(".formData");
//VARIABLES
const xButton = document.querySelector(".close"); // Bouton croix
const subButton = document.querySelector(".button"); //Bouton submit
let firstName = document.querySelector("#firstName"); // Prénom
let lastName = document.querySelector("#lastName"); // Nom
let email = document.querySelector("#email"); //Email
let birthdate = document.querySelector("#birthdate"); //Date de naissance
let nbrTournaments = document.querySelector("#quantity"); //Nbr tournois
let myForm = document.getElementById("reserve");
//Formulaire complet
let emailError = document.querySelector(".mail-error"); //Erreur email
let firstNameError = document.querySelector('.firstname-error'); //Erreur prénom
let lastNameError = document.querySelector('.lastname-error'); //Erreur nom
let tournamentError = document.querySelector('.tournament-error'); //Erreur nbr tournois
let radioError = document.querySelector(".radio-button-error");//Erreur checkbox
let radioButton = document.forms[0].location;//Radio button
let birthdateError = document.querySelector(".birthdate-error");
let checkboxError = document.querySelector(".checkbox-error");
let checkbox = document.querySelector("#checkbox1");
//REGEXP
let emailRegExp = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
let dateRegExp =/^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])$/
//MODAL
// launch modal event
modalBtn.forEach((btn) => btn.addEventListener("click", launchModal));
// launch modal form
function launchModal() {
modalbg.style.display = "block";
}
// close modal event
xButton.addEventListener("click", closeModal);
// close modal form
function closeModal() {
modalbg.style.display = "none";
}
//===================================================================================
//ThanksMODAL CONST
const thanksModalContainer = document.querySelector(".thanks-modal-container"); //ThanksMODAL container
const closeThanksModalBtn = document.querySelector(".thanks-modal-close-btn");
//Modal close button
closeThanksModalBtn.addEventListener("click", closeThanksModal);
// close thanks-modal FUNCTION
function closeThanksModal() {
thanksModalContainer.style.display = "none";
}
//launch thanks-modal EVENT
subButton.addEventListener("submit",launchThanksModal)
//launch thanks-modal FUNCTION
function launchThanksModal() {
thanksModalContainer.style.display = "block";
}
//======================================================================================
//VALIDATION FORMULAIRE
function validate() {
// Validation Prenom
if (firstName.value === "") {
firstNameError.innerHTML = "Votre prénom doit contenir 2 caractères ou plus.";
// return false;
}
// Validation Nom
if (lastName.value === "") {
lastNameError.innerHTML = "Votre nom doit contenir 2 caractères ou plus!";
// return false;
}
//Validation Mail
let testEmail = emailRegExp.test(email.value);
if ((testEmail === false) || (email.value === "")) {
emailError.innerHTML = "Veuillez saisir une adresse email valide.";
// return false;
}
//Validation Date de naissance
let testDate = dateRegExp.test(birthdate.value);
if (testDate === false) {
birthdateError.innerHTML = "Veuillez entrer votre date de naissance.";
// return false;
}
//Validation nombre de tournois
if (nbrTournaments.value === "") {
tournamentError.innerHTML = "Veuillez entrer un nombre";
// return false;
}
//Validation Radio Button
//Boucle vérifier
let valid = false;
for(let i = 0; i < radioButton.length; i++) {
if (radioButton[i].checked){
valid = true;
break;
}
}
if(valid) {
radioError.innerHTML = ""
} else {
radioError.innerHTML = "Veuillez choisir une option";
// return false;
}
//Validation Checkbox
if (checkbox.checked === false) {
checkboxError.innerHTML = "Veuillez lire et valider les conditions."
// return false;
}
if ((!valid||!testDate||!testEmail||!checkbox.checked)||(lastName.value === "")||(firstName.value === "")||(nbrTournaments.value === "")) {
return false;
}
launchThanksModal();
}
My HTML code :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Reservation</title>
<meta name="viewport" content="width=device-width,initial-scale=1" />
<link rel="stylesheet" href="modal.css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link
href="https://fonts.googleapis.com/css?family=DM+Sans"
rel="stylesheet"
/>
</head>
<body>
<div class="topnav" id="myTopnav">
<div class="header-logo">
<img alt="logo" src="Logo.png" width="auto" height="auto" />
</div>
<div class="main-navbar">
<span>Accueil</span>
<span>Détails de l'évènement</span>
<span>À propos</span>
<span>Contact</span>
<span>Évènements passés</span>
<a href="javascript:void(0);" class="icon" onclick="editNav()">
<i class="fa fa-bars"></i>
</a>
</div>
</div>
</div>
<main>
<div class="hero-section">
<div class="hero-content">
<h1 class="hero-headline">
Marathon national<br>
de jeux vidéos
</h1>
<p class="hero-text">
Vous aimez jouer ? Notre prochain évènement gaming est ouvert
aux réservations... Places limitées !
</p>
<button class="btn-signup modal-btn">
je m'inscris
</button>
</div>
<div class="hero-img">
<img src="./bg_img.jpg" alt="img" />
</div>
<button class="btn-signup modal-btn">
je m'inscris
</button>
</div>
<!--MODAL-->
<div class="bground">
<div class="content">
<span class="close"></span>
<div class="modal-body">
<form
id="reserve"
name="reserve"
action="index.html"
method="get"
onsubmit="return validate();"
>
<div
class="formData">
<label for="firstName">Prénom</label><br>
<input
class="text-control"
type="text"
id="firstName"
name="firstName"
minlength="2"
/><br>
<span class="firstname-error errormsg"></span>
</div>
<div
class="formData">
<label for="lastName">Nom</label><br>
<input
class="text-control"
type="text"
id="lastName"
name="lastName"
/><br>
<span class="lastname-error errormsg"></span>
</div>
<div
class="formData">
<label for="email">Email</label><br>
<input
class="text-control"
type="email"
id="email"
name="email"
/><br>
<span class="mail-error errormsg"></span>
</div>
<div
class="formData">
<label for="birthdate">Date de naissance</label><br>
<input
class="text-control"
type="date"
id="birthdate"
name="birthdate"
/><br>
<span class="birthdate-error errormsg"></span>
</div>
<div
class="formData">
<label for="quantity">À combien de tournois GameOn avez-vous déjà participé ?</label><br>
<input type="number" class="text-control" id="quantity" name="quantity" min="0" max="99"><br>
<span class="tournament-error errormsg"></span>
</div>
<p class="text-label">A quel tournoi souhaitez-vous participer cette année ?</p>
<div
class="formData">
<input
class="checkbox-input"
type="radio"
id="location1"
name="location"
value="New York"
/>
<label class="checkbox-label" for="location1">
<span class="checkbox-icon"></span>
New York</label
>
<input
class="checkbox-input"
type="radio"
id="location2"
name="location"
value="San Francisco"
/>
<label class="checkbox-label" for="location2">
<span class="checkbox-icon"></span>
San Francisco</label
>
<input
class="checkbox-input"
type="radio"
id="location3"
name="location"
value="Seattle"
/>
<label class="checkbox-label" for="location3">
<span class="checkbox-icon"></span>
Seattle</label
>
<input
class="checkbox-input"
type="radio"
id="location4"
name="location"
value="Chicago"
/>
<label class="checkbox-label" for="location4">
<span class="checkbox-icon"></span>
Chicago</label
>
<input
class="checkbox-input"
type="radio"
id="location5"
name="location"
value="Boston"
/>
<label class="checkbox-label" for="location5">
<span class="checkbox-icon"></span>
Boston</label
>
<input
class="checkbox-input"
type="radio"
id="location6"
name="location"
value="Portland"
/>
<label class="checkbox-label" for="location6">
<span class="checkbox-icon"></span>
Portland</label
>
</div>
<span class="radio-button-error errormsg"></span>
<div
class="formData">
<input
class="checkbox-input"
type="checkbox"
id="checkbox1"
checked
/>
<label class="checkbox2-label" for="checkbox1" required>
<span class="checkbox-icon"></span>
J'ai lu et accepté les conditions d'utilisation.
</label><p class="checkbox-error errormsg"></p>
<input class="checkbox-input" type="checkbox" id="checkbox2" />
<label class="checkbox2-label" for="checkbox2">
<span class="checkbox-icon"></span>
Je Je souhaite être prévenu des prochains évènements.
</label>
<br>
</div>
<input
class="btn-submit"
type="submit"
class="button"
value="C'est parti"
/>
</form>
</div>
</div>
</div>
<!-- FIN MODAL-->
<!-- MODAL CONFIRMATION ENVOI-->
<div class="thanks-modal-container">
<div class="overlay modal-triggers"></div>
<div class="thanks-modal-content">
<p class="thanks-modal-text">Merci, votre réservation a bien été prise en compte</p>
<button class="thanks-modal-close-btn">OK</button>
</div>
</div>
<!-- FIN MODAL CONFIRMATION ENVOI-->
</main>
<footer>
<p class="copyrights">
Copyright 2014 - 2022, GameOn Inc.
</p>
</footer>
<script src="modal.js"></script>
</body>
</html>
Thanks a lot !
You need event.preventDefault() on form submission so it does not reload the page, and handle your submission logic with only js. Use something like this:
<form onsubmit="submitForm(event)">
<input type="text">
<button type="submit">Submit</button>
</form>
<script>
function submitForm(event){
event.preventDefault();
// your custom submission logic
// display modal on success
}
</script>

Problem showing questions in a quiz made in javascript

I have a form with 5 questions, in which they are displayed one at a time to the user, as in a quiz, that is, the first question appears on the screen, the user answers and goes to the second, and so on.
However, I have a problem with questions 3 and 4, when I don't type anything and press ENTER, question 2 is also appearing on the screen, like the image below:
[![error in questions 3 and 4][1]][1]
[1]: https://i.stack.imgur.com/63pQC.png
I can't show two questions at the same time, just one at a time, and I don't know where I'm going wrong.
Here's the code inside the form tag:
<form class="questions_box formulario" action="enviar-landing-page-v3.php" method="post">
<div id="question-1">
<h3>The question is: ... ?</h3>
<input type="radio" name="objetivo" id="question-1-answer-a" value=1 required oninput="checkObjective()"> Answer 1.<br>
<input type="radio" name="objetivo" id="question-1-answer-b" value=2 oninput="checkObjective()"> Answer 2.<br>
<input type="radio" name="objetivo" id="question-1-answer-c" value=3 oninput="checkObjective()"> Answer 3.<br>
<div class="text-end mt-3">
<input type="submit" id="submit1" class="btn btn-primary btn-lg" value="Enviar Resposta" style="display: none;" />
</div>
<script type="text/javascript">
function checkObjective() {
if (document.getElementsByName('objetivo').value == '') {
document.getElementById('submit1').style.display = 'none';
} else {
document.getElementById('submit1').style.display = 'block';
}
}
</script>
</div>
<div id="question-2">
<h3>Quantos anos tem seu filho(a)?</h3>
<div class="input-formulario">
<i class="far fa-calendar-alt"></i>
<input required type="text" name="idade_aluno_lp" id="idade_aluno_lp" placeholder="Digite a idade do aluno" oninput="checkAge()" maxlength="2" />
</div>
<div class="text-center mt-3">
<input type="submit" id="submit2" class="btn btn-primary btn-lg" value="Enviar Resposta" style="display: none;" />
</div>
<div class="text-end mt-3">
<input type="submit" id="previous2" class="btn btn-primary btn-lg" value="Pergunta Anterior" style="display: block;" />
</div>
<script type="text/javascript">
function checkAge() {
var countAge = document.getElementById('idade_aluno_lp');
countAge.value = countAge.value.replace(/\D/, ''); // Remove caracteres que não sejam números
if (countAge.value.length == 0) { // 0 caracteres digitados
document.getElementById('submit2').style.display = 'none';
} else {
document.getElementById('submit2').style.display = 'block';
}
}
</script>
</div>
<div id="question-3">
<h3>Qual seu nome?</h3>
<div class="input-formulario">
<i class="far fa-user"></i>
<input required type="text" name="nome_lp" id="nome_lp" placeholder="Digite seu nome" oninput="checkName()">
<span id="error-name"></span>
</div>
<div class="text-center mt-3">
<input type="submit" id="submit3" class="btn btn-primary btn-lg" value="Enviar Resposta" style="display: none;" />
</div>
<div class="text-center mt-3">
<input type="submit" id="previous3" class="btn btn-primary btn-lg" value="Pergunta Anterior" style="display: block;" />
</div>
<script type="text/javascript">
function checkName() {
var countName = document.getElementById('nome_lp');
var errorName = document.getElementById('error-name')
countName.value = countName.value.replace(/[0-9]/g, ''); // Remove numbers
if (countName.value.length < 3) { // 0 chars entered
errorName.innerHTML = "O nome precisa ter ao menos 3 caracteres."
document.getElementById('submit3').style.display = 'none';
} else {
errorName.innerHTML = "";
document.getElementById('submit3').style.display = 'block';
}
}
</script>
</div>
<div id="question-4">
<h3>Qual seu email?</h3>
<div class="input-formulario">
<i class="fas fa-at"></i>
<input required type="email" name="email_lp" id="email_lp" placeholder="Digite seu email" oninput="checkEmail()">
<span id="error-email"></span>
</div>
<div class="text-center mt-3">
<input type="submit" id="submit4" class="btn btn-primary btn-lg" value="Enviar Resposta" style="display: none;" />
</div>
<div class="text-end mt-3">
<input type="submit" id="previous4" class="btn btn-primary btn-lg" value="Pergunta Anterior" style="display: block;" />
</div>
<script type="text/javascript">
function checkEmail() {
var email = document.getElementById('email_lp');
var errorEmail = document.getElementById('error-email');
if (!email.checkValidity()) {
errorEmail.innerHTML = "O email deverá seguir o padrão: meuemail#provedor.com";
document.getElementById('submit4').style.display = 'none';
} else {
errorEmail.innerHTML = "";
document.getElementById('submit4').style.display = 'block';
}
}
</script>
</div>
<div id="question-5">
<h3>Qual seu whatsapp?</h3>
<div class="input-formulario">
<i class="fab fa-whatsapp"></i>
<input required type="text" name="celular_lp" id="celular_lp" placeholder="Digite seu DDD + celular" maxlength="14" onkeypress="return mascaraCelular(event)" oninput="checkMobile()">
<span id="error-mobile"></span>
</div>
<div class="text-end mt-3">
<input type="submit" id="submit5" class="btn btn-primary btn-lg" value="Enviar Resposta" style="display: none;" />
</div>
<div class="text-end mt-3">
<input type="submit" id="previous5" class="btn btn-primary btn-lg" value="Pergunta Anterior" style="display: block;" />
</div>
</div>
<script type="text/javascript">
function checkMobile() {
var countMobile = document.getElementById('celular_lp');
var errorMobile = document.getElementById('error-mobile');
if (countMobile.value.length < 13) {
errorMobile.innerHTML = "Além do DDD, o número do celular precisa ter ao menos 8 dígitos";
document.getElementById('submit5').style.display = 'none';
} else {
errorMobile.innerHTML = "";
document.getElementById('submit5').style.display = 'block';
}
}
</script>
</form>
And the javascript responsible for show/hide the questions:
// Variables
var submit1 = document.getElementById('submit1');
var submit2 = document.getElementById('submit2');
var submit3 = document.getElementById('submit3');
var submit4 = document.getElementById('submit4');
var previous2 = document.getElementById('previous2');
var previous3 = document.getElementById('previous3');
var previous4 = document.getElementById('previous4');
var previous5 = document.getElementById('previous5');
// Next question button
submit1.addEventListener('click', function() {
nextQuestion(2);
growProgressBar('40%');
})
submit2.addEventListener('click', function() {
nextQuestion(3);
growProgressBar('60%');
})
submit3.addEventListener('click', function() {
nextQuestion(4);
growProgressBar('80%');
})
submit4.addEventListener('click', function() {
nextQuestion(5);
growProgressBar('100%');
})
// grow Progress Bar
function growProgressBar(percentage_width) {
var bar = document.getElementById('progress_bar');
bar.style.width = percentage_width;
}
// Shows next question, hides current
function nextQuestion(question_number) {
var current_question_number = question_number - 1; //question_number is the next question
var question_number = question_number.toString();
var current_question_number = current_question_number.toString();
document.getElementById('question-' + question_number).style.display = 'block';
document.getElementById('question-' + current_question_number).style.display = 'none';
}
// Previous question button
previous2.addEventListener('click', function() {
previousQuestion(1);
shrinkProgressBar('20%');
})
previous3.addEventListener('click', function() {
previousQuestion(2);
shrinkProgressBar('40%');
})
previous4.addEventListener('click', function() {
previousQuestion(3);
shrinkProgressBar('60%');
})
previous5.addEventListener('click', function() {
previousQuestion(4);
shrinkProgressBar('80%');
})
// Shrink Progress Bar
function shrinkProgressBar(percentage_width) {
var bar = document.getElementById('progress_bar');
bar.style.width = percentage_width;
}
// Shows previous question, hides current
function previousQuestion(question_number) {
var current_question_number = question_number + 1;
var question_number = question_number.toString();
var current_question_number = current_question_number.toString();
var el = document.getElementById('question-' + question_number);
console.log(question_number);
var el2 = document.getElementById('question-' + current_question_number);
el.style.display = 'block';
el2.style.display = 'none';
}
About Carsten Massmann answer:
The problem with the code was just to change the buttons type="submit" to type="button", and leave only the last button as type="submit", however, I really liked your code, I learned a lot, for example, I had never read about closest method. Could you explain to me how these two lines of code work (what they are for I understand):
current = (Q.length + current + inc) % Q.length; // cycle through questions...
Above I don't understand why you use the question length.
And on the next line, I don't understand why I use trim():
(el.value.trim() ? "block" : "none")
I also understand that you cycle between questions, but I need to demarcate the first and last question in the loop, and put something like if Q=0, don't show the "Previous question" button, and if Q=4, that the final button would execute method="POST" and action="next-page". I believe that the "submit" is not being executed because of the loop, but I don't understand why the loop takes precedence over the submit.
The following snippet is still missing your actual validation functions for individual fields but I hope it illustrates the point of how you can avoid unnecessary repetitions in your code and markup. I am using classes to address the various input elements and "delegated event attachment" to combine the click handling for different buttons. For simplicity I allow cycling through the questions. Feel free to change and adapt ...
function changeQ(inc){
current= (Q.length+current+inc)%Q.length; // cycle through questions ...
Q.forEach((q,i)=>q.style.display=(i==current?"":"none"))
}
function showHideOK(el){
let ok=!!el.value.trim();
el.closest(".input-formulario").querySelector("input.ok").style.display=
(ok?"block":"none");
ans[el.name]=ok;
}
document.querySelectorAll("div.input-formulario").forEach((div,i)=>{div.innerHTML+=`<div class="text-end mt-3"><input type="submit" class="btn btn-primary btn-lg back" value="Pergunta Anterior"/></div><div class="text-center mt-3"><input type="submit" class="btn btn-primary btn-lg ok" value="Próxima Pergunta"/></div>`;
div.addEventListener("input",ev=>{ let el=ev.target;
if (el.tagName!=="INPUT") return // only act on input elements ...
showHideOK(el)
btn.style.display=Object.values(ans).filter(a=>a).length==Q.length?"":"none";
});
div.onclick=ev=>{if (ev.target.type=="submit") {
ev.preventDefault();
changeQ( ev.target.classList.contains("back")?-1:1 );
}}
})
const btn = document.querySelector("button"),
Q=document.querySelectorAll(".question"),
ans={};
let current=0;
changeQ(0);
btn.style.display="none";
input.ok {display:none}
<form class="questions_box formulario" action="enviar-landing-page-v3.php" method="post">
<div class="question">
<div class="input-formulario">
<h3>The question is: ... ?</h3>
<label><input type="radio" name="objetivo" value=1 required> Answer 1.</label><br>
<label><input type="radio" name="objetivo" value=2> Answer 2.</label><br>
<label><input type="radio" name="objetivo" value=3> Answer 3.</label><br>
</div>
</div>
<div class="question">
<h3>Quantos anos tem seu filho(a)?</h3>
<div class="input-formulario">
<input required type="number" name="idade_aluno_lp" placeholder="Digite a idade do aluno" maxlength="2" />
</div>
</div>
<div class="question">
<h3>Qual seu nome?</h3>
<div class="input-formulario">
<input required type="text" name="nome_lp" placeholder="Digite seu nome"> <span></span>
</div>
</div>
<div class="question">
<h3>Qual seu email?</h3>
<div class="input-formulario">
<input required type="email" name="email_lp" id="email_lp" placeholder="Digite seu email"> <span></span>
</div>
</div>
<div class="question">
<h3>Qual seu whatsapp?</h3>
<div class="input-formulario">
<input required type="text" name="celular_lp" id="celular_lp" placeholder="Digite seu DDD + celular"
maxlength="14"> <span></span>
</div>
</div>
<br><button>Enviar todas as respostas</button>
</form>
Further explanations:
Why am I using Q.length?
The expression current = (Q.length + current + inc)/Q.length uses Q.length (=total number of questions) to keep current always within the range of existing question indexes. The term Q length+... is necessary to keep values positive for the situation where current=0 and inc=-1 and % Q.length limits the results from 0 to Q.length-1.
Why do I use .trim()?
This is just a simple way of avoiding that an answer containing only blanks would be accepted as a valid answer.
Why is there no "submit"?
I actively disabled the submit action by calling ev.preventDefault() within my event-handling function.
How to submit the answers, and when?
There are many different ways of doing it. My suggestion would be to keep cycling through the questions until all questions are answered in a valid way. At that point an extra button appears that submits all answers at once. I just added that button (btn) to the script. It is hidden at first through btn.style.display="none" but made visible again on the condition that all questions have received an answer:
btn.style.display=Object.values(ans).filter(a=>a).length==Q.length?"":"none";
The (global) object ans is constantly updated in the function showHideOK():
let ok=!!el.value.trim();
...
ans[el.name]=ok;

Using javascript to rewrite input value adding "#"

I want to replace the content of the input entered by adding a "#" in front of it, but at the time of writing the spaces it does not work correctly.
function mayus(texto) {
var text = texto.value.replace('#', '');
var words = text.split(" ");
var newTexto = "";
for (var i = 0; i < words.length; i++) {
if (words[i].length > 0) {
newTexto += "#" + words[i];
} else {
newTexto += " ";
}
}
texto.value = newTexto;
};
<form class="form-horizontal" method="POST" action="addEvent.php">
<div class="form-group">
<label for="etiquetas" class="col-sm-2 control-label">Etiquetas</label>
<div class="col-sm-10">
<textarea name="etiquetas" class="form-control" id="etiquetas" placeholder="escriba y separe con espacio las etiquetas a usar" required onkeyup="mayus(this);" style="color: blue;"> </textarea>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-info" data-dismiss="modal">Cerrar</button>
<button type="submit" class="btn btn-primary">Guardar</button>
</div>
</form>
We can simplify your function. First we look to see if the value already starts with a # using startsWith and if it does we return. If not, we then add it to the beginning.
function mayus(texto) {
let val = texto.value
let result = val.split(' ').map(item => !item.startsWith('#') && item != '' ? '#' + item : item)
texto.value = result.join(' ')
}
<form class="form-horizontal" method="POST" action="addEvent.php">
<div class="form-group">
<label for="etiquetas" class="col-sm-2 control-label">Etiquetas</label>
<div class="col-sm-10">
<textarea name="etiquetas" class="form-control" id="etiquetas" placeholder="escriba y separe con espacio las etiquetas a usar" required onkeyup="mayus(this);" style="color: blue;"></textarea>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-info" data-dismiss="modal">Cerrar</button>
<button type="submit" class="btn btn-primary">Guardar</button>
</div>
</form>
Your else statement should not be there, and you can actually simplify your entire method using a more functional approach. Also use the input event instead of the keyup event to prevent a visual delay.
var previous
function mayus() {
var texto = this.value
.replace(/#/g, '') // removes ALL hashtags
.split(/\s+/g)
.filter(Boolean) // removes empty strings from array of words
.map(function(word) {
return '#' + word;
})
.join(' ');
// add space if key was pressed and output would have been identical
if (previous && texto === previous) {
texto += ' ';
}
previous = this.value = texto;
}
<form class="form-horizontal" method="POST" action="addEvent.php">
<div class="form-group">
<label for="etiquetas" class="col-sm-2 control-label">Etiquetas</label>
<div class="col-sm-10">
<textarea name="etiquetas" class="form-control" id="etiquetas" placeholder="escriba y separe con espacio las etiquetas a usar" required oninput="mayus.call(this);" style="color: blue;"></textarea>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-info" data-dismiss="modal">Cerrar</button>
<button type="submit" class="btn btn-primary">Guardar</button>
</div>
</form>

How to call function D only after function A, B and C are done

Hi guys I'd like to know if its possible to call function "confirm" only IF functions checkV, checkV1, checkV2 are done and the form is completly filled in.
HTML & javascript
http://pastebin.com/xY1MBhv5
function checkV() {
var check = document.getElementById("voornaam").value;
if (isNaN(check) || check.length == 0) {
return true;
} else {
alert("In de naamvelden geen cijfers invoeren s.v.p.");
}
};
function checkV1() {
var check1 = document.getElementById("achternaam").value;
if (isNaN(check1) || check1.length == 0) {
return true;
} else {
alert("In de naamvelden geen cijfers invoeren s.v.p.");
}
};
function checkV2() {
var check2 = document.getElementById("toneelspeler").value;
if (isNaN(check2) || check2.length == 0) {
return true;
} else {
alert("In de naamvelden geen cijfers invoeren s.v.p.");
}
};
function confirm() {
var voorNaam = document.getElementById("voornaam").value;
var toneelNaam = document.getElementById("toneelspeler").value;
var achterNaam = document.getElementById("achternaam").value;
alert("Beste " + voorNaam + " " + achterNaam + ", ontzettend bedankt voor je wens, we zullen ervoor zorgen dat " + toneelNaam + " je wens zal ontvangen!");
};
window.onload = function() {
document.getElementById('submit').onclick = function() {
checkV()
checkV1()
checkV2()
confirm()
};
};
<header>
<div id="logo">
<a href="home.html">
<img src="logo.png" id="home" alt="Logo van Het Imperium Theater">
</a>
<a href="http://www.facebook.com" target="blank">
<img src="facebook.png" id="facebook" alt="facebook" />
</a>
<a href="http://www.twitter.com" target="blank">
<img src="twitter.png" id="twitter" alt="twitter" />
</a>
</div>
<nav>
<ul>
<li>Home
</li>
<li>Agenda
</li>
<li>Het Theater
</li>
<li>Ontdek Leiden
</li>
<li>Contact
</li>
</ul>
</nav>
</header>
<div id="wrapper">
<form id="form" name="form">
<h1>Verstuur een wens.</h1>
<div id="forms">
<label for="voornaam">Voornaam:
<input type="text" name="name" id="voornaam" placeholder="uw voornaam" name="fname" required>
</label>
<label for="achternaam">Achternaam:
<input type="text" name="name" id="achternaam" placeholder="uw achternaam" name="fname" required>
</label>
<label for="toneelspeler">Naam toneelspeler:
<input type="text" name="name" id="toneelspeler" placeholder="naam van de toneelspeler" name="fname" required>
</label>
<label for="boodschap">Uw wens:
<textarea rows="4" cols="20" name="name" placeholder="Type hier uw wens" required></textarea>
</label>
</div>
<input type="submit" value="Submit" id="submit">
</form>
</div>
<footer>
<a href="home.html">
<p>Theater Imperium</p>
</a>
<p>Oude Vest 33e</p>
<p>2312 XR Leiden</p>
<p>071 5141035</p>
<p>© Arpiar Melikjan</p>
</footer>
According to the link provided, if everything goes fine, checkV(), checkV1() and checkV2() will return true, otherwise undefined. You can do something like this:
if(checkV() && checkV1() && checkV2())
//Do submit
EDIT:
If you want more control over your control flow (which might be helpful in debugging), you might do something like this:
if(checkV()) {
if(checkV1()) {
if(checkV2()) {
//Do submit
}
}
}
Now, you can associate else blocks, and can take action according to the method which failed to validate your input.

how to fill the star rating according to the votes

how do I fill the stars of a star rating already everything running the calculation and it took a echo in the variable calculation to see the result he would return me and he is me returning right however I am unable to leave it filled for example to note that 3.3 product and fill it three stars and 30% of the fourth as I do it? where I have to play my variable to show it in the stars?
code:
<form id="rating" action"rating.php" method="post">
<input type="hidden" name="id" id="idd" value="$idprod" />
<div class="vote">
<label>
<input id="stars" class="radioo" type="radio" name="fb" value="1" />
<i class="fa" id="fa"></i>
</label>
<label>
<input id="stars" class="radioo" type="radio" name="fb" value="2" />
<i class="fa" id="fa"></i>
</label>
<label>
<input id="stars" class="radioo" type="radio" name="fb" value="3" />
<i class="fa" id="fa"></i>
</label>
<label>
<input id="stars" class="radioo" type="radio" name="fb" value="4" />
<i class="fa" id="fa"></i>
</label>
<label>
<input id="stars" class="radioo" type="radio" name="fb" value="5" />
<i class="fa" id="fa"></i>
</label>
</div>
</form>
jquery:
$('.vote label i.fa').on('click mouseover',function(){
// remove classe ativa de todas as estrelas
$('.vote label i.fa').removeClass('active');
// pegar o valor do input da estrela clicada
var val = $(this).prev('input').val();
//percorrer todas as estrelas
$('.vote label i.fa').each(function(){
/* checar de o valor clicado é menor ou igual do input atual
* se sim, adicionar classe active
*/
var $input = $(this).prev('input');
if($input.val() <= val){
$(this).addClass('active');
}
});
$("#voto").html(val); // somente para teste
});
//Ao sair da div vote
$('.vote').mouseleave(function(){
//pegar o valor clicado
var val = $(this).find('input:checked').val();
//se nenhum foi clicado remover classe de todos
if(val == undefined ){
$('.vote label i.fa').removeClass('active');
} else {
//percorrer todas as estrelas
$('.vote label i.fa').each(function(){
/* Testar o input atual do laço com o valor clicado
* se maior, remover classe, senão adicionar classe
*/
var $input = $(this).prev('input');
if($input.val() > val){
$(this).removeClass('active');
} else {
$(this).addClass('active');
}
});
}
$("#voto").html(val); // somente para teste
});
php:
$id = $_GET['cod'];
$sql = mysql_query("SELECT * FROM produtos WHERE id_produto = $id");
$test = mysql_query("SELECT votos, pontos FROM produtos WHERE id_produto = $id");
$aux = mysql_fetch_array($sql);
$idprod = $aux['id_produto'];
$row = mysql_fetch_array($test);
$voto = $row['votos'];
$ponto = $row['pontos'];
$calc = round(($ponto/$voto),1);
If I understand your question correctly, you are not sure how to fill stars dynamically from a PHP value for a calculated rating.
I put together this solution, the fiddle is here. The best way to do this (outside of AJAX) is to pass the calculated rating into a data attribute on the rating element. Then have your JS fill stars based on that as is shown in the jQuery. I also shown how you can use a click event to fill a hidden input field and re-evalulate the star filling to represent what was clicked.
If later a form is not submitted, you can post the new rating via ajax (best solution really to avoid a page change just to add a new rating). Or if a form is submitted, just make sure the divs are inside the element.
Here the code:
PHP:
//Do your calcuations
$calc = round(($ponto/$voto),1);
HTML
<div class="rating" data-calc="<?php echo $calc; ?>">
<div class="star" data-seq="1">
<div class="cnt">
<img class="full" src="https://upload.wikimedia.org/wikipedia/commons/thumb/2/2e/Stj%C3%A4rna.svg/2000px-Stj%C3%A4rna.svg.png" />
</div>
<img class="empty" src="https://upload.wikimedia.org/wikipedia/commons/thumb/1/18/Five-pointed_star.svg/1088px-Five-pointed_star.svg.png" />
</div>
<div class="star" data-seq="2" >
<div class="cnt">
<img class="full2" src="https://upload.wikimedia.org/wikipedia/commons/thumb/2/2e/Stj%C3%A4rna.svg/2000px-Stj%C3%A4rna.svg.png" />
</div>
<img class="empty" src="https://upload.wikimedia.org/wikipedia/commons/thumb/1/18/Five-pointed_star.svg/1088px-Five-pointed_star.svg.png" />
</div>
<div class="star" data-seq="3">
<div class="cnt">
<img class="full" src="https://upload.wikimedia.org/wikipedia/commons/thumb/2/2e/Stj%C3%A4rna.svg/2000px-Stj%C3%A4rna.svg.png" />
</div>
<img class="empty" src="https://upload.wikimedia.org/wikipedia/commons/thumb/1/18/Five-pointed_star.svg/1088px-Five-pointed_star.svg.png" />
</div>
<div class="star" data-seq="4">
<div class="cnt">
<img class="full" src="https://upload.wikimedia.org/wikipedia/commons/thumb/2/2e/Stj%C3%A4rna.svg/2000px-Stj%C3%A4rna.svg.png" />
</div>
<img class="empty" src="https://upload.wikimedia.org/wikipedia/commons/thumb/1/18/Five-pointed_star.svg/1088px-Five-pointed_star.svg.png" />
</div>
<div class="star" data-seq="5">
<div class="cnt">
<img class="full" src="https://upload.wikimedia.org/wikipedia/commons/thumb/2/2e/Stj%C3%A4rna.svg/2000px-Stj%C3%A4rna.svg.png" />
</div>
<img class="empty" src="https://upload.wikimedia.org/wikipedia/commons/thumb/1/18/Five-pointed_star.svg/1088px-Five-pointed_star.svg.png" />
</div>
<input type="hidden" name="rating" value="" />
</div>
jQuery
function fillStarOnPercent(star, percent)
{ var fill = 25 * percent;
star.children('.cnt').css({'width' : fill +'px'});
}
function fillStars(parent, fullStars, percent){
for(var i = 1; i < 6; i++)
{
var star = parent.find('.star[data-seq="'+i+'"]');
if(i < fullStars)
fillStarOnPercent(star, 1);
if(i == fullStars)
fillStarOnPercent(star, percent);
if(i > fullStars)
fillStarOnPercent(star, 0);
}
}
$(document).ready(function() {
jQuery('.rating').each(function() {
var calc = jQuery(this).data('calc');
var fullStars = Math.floor(calc);
if(fullStars == calc)
var percent = 1
else
var percent = calc - fullStars;
fillStars( jQuery(this), fullStars, percent );
});
jQuery('.rating').on('click', '.star', function() {
var rating = jQuery(this).data('seq');
fillStars(jQuery(this).parent(), rating, 1 );
jQuery(this).parent().children('input[name="rating"]').val(rating);
});
});
CSS
.star {width:25px;height:25px; position:relative; float:left;}
.star img {display:block; position:absolute; top:0; left:0; width:25px; height:25px;}
.cnt {position:absolute; top:0; left:0; overflow:hidden; width:25px; height:25px}

Categories

Resources