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>
Related
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;
I`ve building a login page and I would like to redirect the user to another html page only if the Html textbox and password were filled (with anything).
My idea is using only Html and Javascript to do it (as far as I don`t need php to send the data).
So here is my html, the forms part specifically
<form name="frmTeste" onsubmit="return validaForm(this);">
<fieldset id="usuario">
<legend id="usuario" >Identificação do Usuário</legend>
<p>Nº <input type="text" name="tNumero" id="tNumero" size="20" maxlength="15" placeholder="ID"> </p>
<p><label for="cSenha" >Senha:</label> <input type="password" name="tSenha" id="cSenha" size="20" maxlength="12" placeholder="Senha" autocomplete="current-password"/> </p>
<input type="submit" id="botao" class="bt bt-acessar" value="Entrar" onclick="Nova(this)">
<p>
Não possui uma conta? Cadastrar
</p>
</fieldset>
</form>
And here is my javascript
function validaForm(frm) {
if(frm.tNumero.value == "" || frm.tNumero.value == null || frm.tNumero.value.lenght < 3) {
alert("Por favor, indique o seu numero USP.");
frm.nome.focus();
return false;
}else if(frm.cSenha.value == "" || frm.cSenha.value == null || frm.cSenha.value.lenght < 3){
alert("Por favor, indique sua senha");
frm.nome.focus();
return false;
}else{
return true;
}
}
function Nova(frm){
if (validaForm(frm) == false){
location.href = "index.html";
}else if (validaForm(frm) == true){
location.href = "notas.html";
}
I`ve trying a lot of different ways but with no sucess at all.
I think this is what you looking for.
You should change
<form name="frmTeste">
<fieldset id="usuario">
<legend id="usuario" >Identificação do Usuário</legend>
<p>Nº <input type="text" name="tNumero" id="tNumero" size="20" maxlength="15" placeholder="ID"> </p>
<p><label for="cSenha" >Senha:</label> <input type="password" name="tSenha" id="cSenha" size="20" maxlength="12" placeholder="Senha" autocomplete="current-password"/> </p>
<input type="submit" id="botao" class="bt bt-acessar" value="Entrar" onclick="validateForm(this)">
<p>
Não possui uma conta? Cadastrar
</p>
</fieldset>
</form>
Also change the javascript
function validateForm(frm){
window.event.preventDefault();
frm = frm.parentNode.parentNode;
var tNumero = document.getElementById("tNumero");
var cSneha = document.getElementById("cSenha");
if(tNumero.value.length < 3) {
alert("Por favor, indique o seu numero USP.");
window.location.href = "/index.html";
} else if(cSenha.value.length < 3){
alert("Por favor, indique sua senha");
window.location.href = "/index.html";
}else{
frm.setAttribute("action","/notas.html");
frm.submit();
}
}
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 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}
Ok, i have this form:
<div id="reg_mov" title="Agregar Movimiento" style="display:none;">
<form style="width:590px;" method="POST" action="saveMovement.php" onSubmit="return checkFormAndSubmit(this)">
<br>
<input style="display:none;" type="text" name="cliente" value=<?php echo $_GET['cliente']; ?>>
<label>Fecha: </label>
<input type="date" name="fecha_mov" /><br><br>
<label>Inversion del Dia: </label>
<input type="text" name="inversion_mov" />
<label>Tipo de Cambio: </label>
<input type="text" name="tipo_cambio" /><br />
<label>Crecimiento de Fans: </label>
<input type="text" name="fans" />
<input type="checkbox" name="corte" />
<label>Corte</label><br /><br />
<label style="color:#486288; font-size:16px; font-weight:600;">Depósito</label><br><br>
<label>Cantidad: </label>
<input type="text" name="cantidad_deposito" />
<label>Dato de Pago: </label>
<select id="datoPago" name="dato_pago" onChange="checkValue()" ><option>Credito</option><option>Deposito</option></select><br /><br />
<label id="Tarjeta" >Tarjeta: </label>
<input class="Tarjeta" type="text" name="tarjeta" />
<label id="Notas">Notas: </label>
<textarea style="font-size:10px;"cols="30" maxlenght="200" name="notas"></textarea>
<br /><br />
<button style="margin-left:230px;" onClick="submitThisForm(this.form)">Guardar</button>
<button style="margin-left:10px;" onClick="closeDialog()">Cancelar</button>
</form>
And i validate it with this javascript code:
function checkFormAndSubmit(form){
if(form.fecha_mov.value == null || form.fecha_mov.value == "")
{
alert('Selecciona una fecha correcta por favor');
return false;
}
else
{
if(!form.inversion_mov.value.match(/^-?\d+$/) || !form.inversion_mov.value.match(/^-?\d+*\.\d+$/))
{
alert('Ingresa un valor valido para la Inversión del Dia');
return false;
}
else
{
if(!form.tipo_cambio.value.match(/^-?\d+$/) || !form.tipo_cambio.value.match(/^-?\d+*\.\d+$/))
{
alert('Ingresa un valor válido para el Tipo de Cambio');
return false;
}
else
{
if(!form.fans.value.match(/^-?\d+$/))
{
alert('Ingresa un valor válido para el número de Fans');
return false;
}
else
{
if(form.cantidad_deposito.value != "")
{
if(!form.cantidad_deposito.value.match(/^-?\d+$/) || !form.cantidad_deposito.value.match(/^-?\d+*\.\d+$/))
{
alert('Ingresa un valor válido para la Cantidad del Depósito');
return false;
}
else
{
return true;
}
}
}
}
}
}
}
I present the form using jquery UI dialog:
$(function(){
$("#reg_mov").dialog({
height:350,
width:610,
modal:true,
});
});
When i hit the button that i define for submitting it runs the validation and if there's an error it displays the same alert twice and then it still submits the form. How do i stop the submitting thing or what's the right way of doing this validation?