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;
Related
I want to hide the divi when I click the button and open it when I click it again. But I couldn't run the normally working code, what could be the reason?
The js code works when there is only one div, but it does not work due to this code I wrote, but I can't solve the problem.
Razor Page
#for (int i = 0; i < Model.quest.Count; i++)
{
<div class="row mt-12" >
<div class="col-md-1">
<input type="checkbox" id="questcb" asp-for="#Model.quest[i].check">
<span>#(i + 1) Soru</span>
</div>
<div class="col-md-9">
<textarea class="form-control" asp-for=#Model.quest[i].Question rows="3" id="question" hidden></textarea>
<label>#Model.quest[i].Question</label>
</div>
</div>
<div class="row mt-12">
<div class="col-md-1" hidden>
<button class="btn btn-outline-secondary" type="button" id="A" onclick="clickFunc(this.id)">A</button>
</div>
<div class="col-md-1" >
A)
</div>
<div class="col-md-11" hidden="hidden">
<input type="text" asp-for=#Model.quest[i].Answer1 class="form-control" placeholder="" id="answer"
aria-label="Example text with button addon" aria-describedby="button-addon1">
</div>
<div class="col-md-11" id="Amod_#i" style="display:inline-block">
#Model.quest[i].Answer1
</div>
<div class="col-md-2">
<button class="btn btn-primary" type="button" id="mod_#i" onclick="question(this.id)">Cevapları Görüntüle</button>
</div>
</div>
}
js code
let question = button => {
let element = document.getElementById(`A${button}`);
let buttonDOM = document.getElementById(`${button}`)
let hidden = element.getAttribute("hidden");
if (hidden) {
element.removeAttribute("hidden");
buttonDOM.innerText = "Cevapları Gizle";
}
else {
element.setAttribute("hidden", "hidden");
buttonDOM.innerText = "Cevapları Görüntüle";
}
}
</script>
If the id of div is unique in your code,your js should work.If it still doesn't work,you can try to find the div with the position of the button:
let question = button => {
let element = $("#" + button).parent().siblings(".col-md-11")[1];
let buttonDOM = document.getElementById(`${button}`);
if (element.hidden) {
element.removeAttribute("hidden");
buttonDOM.innerText = "Cevapları Gizle";
}
else {
element.setAttribute("hidden", "hidden");
buttonDOM.innerText = "Cevapları Görüntüle";
}
}
result:
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>
I'm creating a comment and reply system, but I can't get the reply button to display the input field for only the comment.
When the any reply button is clicked, all the input fields displays instead of just the one clicked
This is my javascript:
function reply() {
var doc;
doc=document.getElementsByClassName("sho") ;
for (var i = 0 ; i < doc.length; i++){
doc[i].style.display="block ";
}
}
$('.btn-reply').on("click", function () {
var parent_dom = $(this).parent();
var _input_child_dom = $(parent_dom).children("input");
var find_allInput = $('.reply-container').find("input");
if(find_allInput.length > 0 ){
for (var i = 0; i < find_allInput.length; i++) {
$(find_allInput[i]).css("display" , "none");
}
}
$(_input_child_dom).css("display" , "block");
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="reply-container">
<div class="reply">
<p>First reply</p>
<button class="btn btn-primary btn-reply">reply</button>
<input type="text" class="InputReply" style="display: none;">
</div>
<br>
<div class="reply">
<p>Second reply</p>
<button class="btn btn-primary btn-reply">reply</button>
<input type="text" class="InputReply" style="display: none;">
</div>
<br>
<div class="reply">
<p>Third reply</p>
<button class="btn btn-primary btn-reply">reply</button>
<input type="text" class="InputReply" style="display: none;">
</div>
</div>
Note: This is the idea of how you can achieve your requirement.
I have a form that, when clicked, redirects to a page. However, I want that in addition, when the click happens, it activates a counter and that this counter keeps showing up even after the page is closed.
I tried to do this with localstorage, I can store the first click, but I can't display or store the others
This is my code
document.getElementById('contadorInscritos').value = localstorage.contadorInscritos;
var salvarClique = function() {
var clickcount = document.getElementById('contadorInscritos').value;
localStorage.setItem('contadorInscritos', 'contadorInscritos');
}
document.onclick = salvarClique
let contadorInscritos = 0;
function clickbutton(){
contadorInscritos ++;
document.querySelector('#contadorInscritos').innerHTML = contadorInscritos * 5 + ' novos inscritos';
}
<form id="forms_layout">
<div>
<div class="email labels" id="email_label_mail">
<input class="input_labels" id="email" maxlength="80" name="email" type="email" size="20" required />
<span class="placeholder_input" data-placeholder="E-mail"></span>
</div>
<span id="email_message_error" class="message_error">Email inválido.</span>
<div class="first_name labels" id="email_label_name">
<input class="input_labels" id="first_name" maxlength="40" name="first_name" size="20" required />
<span class="placeholder_input" data-placeholder="Nome"></span>
</div>
<span id="first_name_message_error" class="message_error">Nome obrigatório.</span>
<div class="phone labels" id="email_label_phone">
<input title="Insira um formato de telefone válido" class="input_labels" id="phone" minlength="15" maxlength="15" name="phone" size="20" pattern="(d{2})d{5}-d{4}" />
<span class="placeholder_input" data-placeholder="Celular"></span>
</div>
<span id="phone_message_error" class="message_error">Formato de Telefone inválido.</span>
</div>
<div class="connect_icon py-1">
<button id="button_layout" class="button_layout" type="button" onclick="clickbutton()">
<b id="lblBotao">QUERO ME INSCREVER</b>
<div id="divSpiner" class="spinner-border" role="status" style="display: none;">
<span class="sr-only">Enviando...</span>
</div>
<div class="send__icon">
<i class="fa fa-chevron-right" aria-hidden="true"></i>
</div>
</button>
</div>
<p style="color: white; font-weight: 600; padding-top: 10px; text-align: center;">
<span id="contadorInscritos"> novos inscritos</span>
</p>
</form>
When fetching data from localStorage you need to use the getItem
method.
When you use setItem, you are passing the second argument as a string, rather than as a variable.
I suggest you keep the counter element separate.
// save counter element to a variable:
var counterElement = document.getElementById('contadorInscritos');
// fetch contadorInscritos from localStorage
var contadorInscritos = localStorage.getItem('contadorInscritos');
// in case there is no value already in localStorage:
if (!contadorInscritos) { contadorInscritos = 0; }
// update the dom with the vale fetched from storage:
counterElement.innerText = contadorInscritos * 5;
// save contadorInscritos to localStorage whenever document is clicked
var salvarClique = function (event) {
localStorage.setItem('contadorInscritos', contadorInscritos);
};
document.onclick = salvarClique;
// handle button clicks:
function clickbutton() {
contadorInscritos++;
counterElement.innerHTML = contadorInscritos * 5;
}
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>