Multiple toggles using javaScript not jquery - javascript

I'm currently trying to make a page with an overlay that toggles once the form is correctly filled out then submitted. Once the first form is submitted it should take you to another. Both forms are in the html already, first overlay works but second does not.
function formValidator() {
var firstname = document.getElementById('firstname');
var lastname = document.getElementById('lastname');
var email = document.getElementById('email');
var phone = document.getElementById('phone');
// Check each input in the order that it appears in the form!
if (notEmpty(firstname, "Cannot leave First Name empty")) {
if (notEmpty(lastname, "Cannot leave Last Name empty")) {
if (notEmpty(phone, "Cannot leave Phone # empty")) {
if (notEmpty(email, "Cannot leave Email empty")) {
if (isAlphabet(firstname, "Please enter only letters for your first name")) {
if (isAlphabet(lastname, "Please enter only letters for your last name")) {
if (phoneValidator(phone, "Numbers only for phone # in the xxx-xxx-xxxx format")) {
if (emailValidator(email, "Please enter a valid email address")) {
return true;
}
}
}
}
}
}
}
}
return false;
}
function notEmpty(elem, helperMsg){
if(elem.value.length == 0){
alert(helperMsg);
elem.focus(); // set the focus to this input
return false;
}
return true;
}
function isAlphabet(elem, helperMsg){
var alphaExp = /^[a-zA-Z]+$/;
if(elem.value.match(alphaExp)){
return true;
}else{
alert(helperMsg);
elem.focus();
return false;
}
}
function phoneValidator(elem, helperMsg){
var alphaExp = /^\(?(\d{3})\)?[- ]?(\d{3})[- ]?(\d{4})$/;
if(elem.value.match(alphaExp)){
return true;
}else{
alert(helperMsg);
elem.focus();
return false;
}
}
function emailValidator(elem, helperMsg){
var emailExp = /^[\w\-\.\+]+\#[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;
if(elem.value.match(emailExp)){
return true;
}else{
alert(helperMsg);
elem.focus();
return false;
}
}
function formValidator2(){
var dropdown1 = document.getElementById('selection').value;
var dropdown2 = document.getElementById('selection2').value;
var dropdown3 = document.getElementById('selection3').value;
var dropdown4 = document.getElementById('selection4').value;
var dropdown5 = document.getElementById('selection5').value;
if(dropdown1 == ""){
alert("Please make a selection (Job Category)");
return false;
}
if(dropdown2 == ""){
alert("Please make a selection (Job Title)");
return false;
}
if(dropdown3 == ""){
alert("Please make a selection (Highest Education Level)");
return false;
}
if(dropdown4 == ""){
alert("Please make a selection (High School Graduation Year)");
return false;
}
if(dropdown5 == ""){
alert("Please make a selection (Further Education)");
return false;
}else{
return true;
}
}
/*I am currently unable to toggle from box1 to box2*/
function toggleOverlay(){
var overlay = document.getElementById('overlay');
var specialBox = document.getElementById('Box1');
var specialBox1 = document.getElementById('Box2');
overlay.style.opacity = .7;
if(overlay.style.display == "block"){
overlay.style.display = "none";
specialBox.style.display = "none";
specialBox1.style.display = "none";
} else if (specialBox.style.display == "block" && overlay.style.display == "block") {
overlay.style.display = "block";
specialBox1.style.display = "block";
specialBox.style.display = "none";
} else {
overlay.style.display = "block";
specialBox.style.display = "block";
}
}
body{
height: 100vmin;
margin-top: 0;
}
.header {
background-color: #F1F5FA;
}
.header p:first-child {
color: #4AC3E8;
margin: 0;
padding-top: 2%;
text-align: center;
font-size: 2.5vmin;
}
.header p:nth-child(2) {
color: #D3D3D8;
margin-top: 1%;
text-align: center;
padding-bottom: 2%;
}
.dark-blue {
color: #0080A4;
}
.text {
color: #00479B;
font-size: 3vmin;
}
.text2 {
color: #00479B;
font-size: 2vmin;
}
.input {
width: 30%;
margin-left: 3%;
height: 30px;
}
.spacing2 {
margin-left: 24%;
}
.spacing3 {
margin-left: 28%;
}
.button {
display: block;
margin-left: auto;
margin-right: auto;
margin-top: 5%;
width: 35%;
background-color: #008BBF;
color: white;
border-radius: 5px;
height: 50px;
font-weight: bold;
}
#main p {
color: #C6C8c8;
padding-left: 15%;
padding-right: 15%;
font-size: 1.5vmin;
margin-top: 5%;
}
.underline {
text-decoration: underline;
}
#skip {
background-color: #D7D7D7;
border-radius: 5px;
display: block;
margin-left: auto;
margin-right: auto;
width: 35%;
height: 30px;
color: #585858;
font-weight: bold;
margin-top: 3%;
}
form {
text-align: center;
}
form p {
font-size: 2.5vmin;
}
select {
width: 25%;
}
#paragraph {
color: #c6c8c8;
padding-left: 15%;
padding-right: 15%;
}
div#overlay {
display: none;
z-index: 2;
background: #000;
position: fixed;
width: 100%;
height: 100%;
top: 0;
left: 0;
text-align: center;
}
div#Box1 {
display: none;
position: fixed;
z-index: 3;
width: 70%;
height: 85%;
background: #FFF;
color: #000;
margin-left: 15%;
margin-top: 5%;
margin-bottom: 5%;
top: 0;
}
div#wrapper {
height: 1000px;
text-align: center;
margin-top: 10%;
}
div#Box2 {
display: none;
position: fixed;
z-index: 3;
width: 70%;
height: 85%;
background: #FFF;
color: #000;
margin-left: 15%;
margin-top: 5%;
margin-bottom: 5%;
top: 0;
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="interview.css">
<script type="text/javascript" src="validation.js"></script>
</head>
<body>
<!-- Start Overlay -->
<div id="overlay"></div>
<!-- End Overlay -->
<!-- Start Special Centered Box -->
<div id="Box1">
<div class="header">
<p>WE FOUND <span class="dark-blue">ALL JOBS</span> NEAR 94536</p>
<p>To get started, enter your contact information to see qualified job offers in your area.</p>
</div>
<div id="main">
<form id="form" onsubmit='return formValidator()'>
<span class="text spacing">First Name:</span><span class="text spacing2">Last Name:</span><br>
<input type="text" id="firstname" class="input">
<input type="text" id="lastname" class="input"> <br>
<span class="text spacing">Phone:</span><span class="text spacing3">Email:</span><br>
<input type="text" id="phone" class="input">
<input type="text" id="email" class="input"><br>
<button type="submit" form="form" class="button" onsubmit="toggleOverlay()">SUBMIT</button>
</form>
<!--Normally terms and conditions would be a link instead of underline below-->
<p>By submitting my information, I agree to the <span class="underline">Terms and Conditions</span> and <span class="underline">Privacy Policy.</span></p>
<p>By clicking continue, I consent to be contacted regarding education opportunities at the phone number provided,
including mobile number, using an automated telephone dialing system. I may be contacted by 2 of the following:
College Achieve, College Complete, Education Bridge, US News Univ. Connection, Career Advisor, or preferred partners.
Consent is not required as a condition of using this service.</p>
<button type="submit" id='skip' onmousedown="toggleOverlay()">SKIP TO RESULTS</button>
</div>
</div>
<div id="Box2">
<div class="header">
<p>While we generate your <span class="dark-blue">ALL JOBS</span> search results, please complete your profile for a more targeted search......</p>
<p>Your ALL JOBS will display shortly.</p>
</div>
<div>
<form id="form2" onsubmit='return formValidator2()'>
<p class="text2">Job Category</p>
<select id="selection">
<option value=""></option>
<option>Govt Services</option>
<option>Food</option>
<option>Entertainment</option>
<option>Internet</option>
</select>
<p class="text2">Job Title</p>
<select id="selection2">
<option value=""></option>
<option>Mechanic</option>
<option>Web Developer</option>
<option>Server</option>
<option>Accountant</option>
</select>
<p class="text2">Highest Education Level?</p>
<select id="selection3">
<option value=""></option>
<option>High School</option>
<option>Some College</option>
<option>College</option>
<option>Masters</option>
</select>
<p class="text2">High School Graduation Year?</p>
<select id="selection4">
<option value=""></option>
<option>2000</option>
<option>1999</option>
<option>1998</option>
<option>1997</option>
<option>1996</option>
<option>1995</option>
<option>1994</option>
<option>1993</option>
</select>
<p class="text2">Are You Interested in Furthering Your Education?</p>
<select id="selection5">
<option value=""></option>
<option>Yes</option>
<option>No</option>
</select> <br>
<button type="submit" form="form2" class="button">CONTINUE</button>
</form>
<p id="paragraph">
By clicking continue, I consent to be contacted regarding education opportunities at the phone number provided,
including mobile number, using an automated telephone dialing system. I may be contacted by 2 of the following:
College Achieve, College Complete, Education Bridge, US News Univ. Connection, Career Advisor, or preferred partners.
Consent is not required as a condition of using this service.
</p>
</div>
</div>
<!-- Start Special Centered Box -->
<!-- Start Normal Page Content -->
<div id="wrapper">
<button onmousedown="toggleOverlay()">Apply Overlay</button>
</div>
<!-- End Normal Page Content -->
</body>
</html>

You have couple of places to correct.
Form submission triggers to reload the whole page (equals start
over).
After first form submission all boxes are hidden, so you can not
check their display attributes.
To correct the first issue always return false but call overlay before that:
function formValidator() {
var firstname = document.getElementById('firstname');
var lastname = document.getElementById('lastname');
var email = document.getElementById('email');
var phone = document.getElementById('phone');
// Check each input in the order that it appears in the form!
if (notEmpty(firstname, "Cannot leave First Name empty")) {
if (notEmpty(lastname, "Cannot leave Last Name empty")) {
if (notEmpty(phone, "Cannot leave Phone # empty")) {
if (notEmpty(email, "Cannot leave Email empty")) {
if (isAlphabet(firstname, "Please enter only letters for your first name")) {
if (isAlphabet(lastname, "Please enter only letters for your last name")) {
if (phoneValidator(phone, "Numbers only for phone # in the xxx-xxx-xxxx format")) {
if (emailValidator(email, "Please enter a valid email address")) {
toggleOverlay();
}
}
}
}
}
}
}
}
return false;
}
To correct second issue I have introduced the counter, on how many times the ApplyOverlay button was clicked. Based on its value, different form is displayed:
/*I am currently unable to toggle from box1 to box2*/
// This should fix it
var counter = 0;
function toggleOverlay(){
var overlay = document.getElementById('overlay');
var specialBox = document.getElementById('Box1');
var specialBox1 = document.getElementById('Box2');
overlay.style.opacity = .7;
if (counter==1) {
overlay.style.display = "none";
specialBox.style.display = "none";
specialBox1.style.display = "none";
} else if (counter==2) {
overlay.style.display = "block";
specialBox1.style.display = "block";
specialBox.style.display = "none";
} else {
overlay.style.display = "block";
specialBox.style.display = "block";
}
counter++;
}

Related

Rest button at the end of the quiz is not functioning

When the user gets to the end of this quiz a reset button is present. I have tried everything I can find to make the reset button work. I've added it to the top, I've wrapped in a form tag as well and tried "reset form". I'm a novice, so I would appreciate knowing what I may be doing wrong and if this is even a possibility with my current formatting.
Full code below.
var currentTab = 0; // Current tab is set to be the first tab (0)
showTab(currentTab); // Display the current tab
// Displays the specified tab of the form
function showTab(n) {
var x = document.getElementsByClassName('tab');
x[n].style.display = 'block';
// Fix the Previous button
if (n == 0) {
document.getElementById('prevBtn').style.display = 'none';
} else {
document.getElementById('prevBtn').style.display = 'inline';
}
// Fix the Next button
if (n == (x.length - 1)) {
document.getElementById('nextBtn').innerHTML = 'restart';
} else {
document.getElementById('nextBtn').innerHTML = 'Next';
}
// Run a function that will display the correct step indicator
fixStepIndicator(n)
}
// Figures out which tab to display
function nextPrev(n) {
var x = document.getElementsByClassName('tab');
// Exit the function if any field in the current tab is invalid
if (n == 1 && !validateForm()) return false;
// Hide the current tab
x[currentTab].style.display = 'none';
// Increase or decrease the current tab by 1
currentTab = currentTab + n;
// if you have reached the end of the form...
if (currentTab >= x.length) {
// ... the form gets restarted:
document.getElementById('regForm').restart();
return false;
}
// Otherwise, display the correct tab:
showTab(currentTab);
}
// Validates the form fields
function validateForm() {
var x, y, i, valid = true;
x = document.getElementsByClassName('tab');
y = x[currentTab].getElementsByTagName('input');
// Checks every input field in the current tab:
for (i = 0; i < y.length; i++) {
// If a field is empty...
if (y[i].value == '') {
// add an "invalid" class to the field
y[i].className += ' invalid';
// and set the current valid status to false
valid = false;
}
}
// If the valid status is true, mark the step as finished and valid:
if (valid) {
document.getElementsByClassName('step')[currentTab].className += ' finish';
}
return valid; // return the valid status
}
// Removes the "active" class of all steps
function fixStepIndicator(n) {
var i, x = document.getElementsByClassName('step');
for (i = 0; i < x.length; i++) {
x[i].className = x[i].className.replace(' active', '');
}
//... and add the "active" class on the current step
x[n].className += ' active';
}
function yesnoCheck() {
if (document.getElementById('yesCheck').checked) {
document.getElementById('ifYes').style.display = 'block';
} else {
document.getElementById('ifYes').style.display = 'none';
}
if (document.getElementById('noCheck').checked) {
document.getElementById('ifNo').style.display = 'block';
} else {
document.getElementById('ifNo').style.display = 'none';
}
}
function yesno1Check() {
if (document.getElementById('yes1Check').checked) {
document.getElementById('ifYes1').style.display = 'block';
} else {
document.getElementById('ifYes1').style.display = 'none';
}
if (document.getElementById('no1Check').checked) {
document.getElementById('ifNo1').style.display = 'block';
} else {
document.getElementById('ifNo1').style.display = 'none';
}
}
* {
box-sizing: border-box;
}
body {
background-color: #f1f1f1;
padding-bottom: 5rem;
}
#regForm {
background-color: #ffffff;
margin: 50px auto;
font-family: calibri;
font-size: 17px
padding: 40px;
width: 30%;
min-width: 300px;
}
h1 {
text-align: center;
}
input {
padding: 10px;
width: 100%;
font-size: 17px;
font-family: Raleway;
border: 1px solid #aaaaaa;
}
/* Mark input boxes that gets an error on validation: */
input.invalid {
background-color: #ffdddd;
}
/* Hide all steps by default: */
.tab {
display: none;
}
button {
background-color: #0000ff;
color: #ffffff;
border: none;
padding: 10px 20px;
font-size: 17px;
font-family: Raleway;
cursor: pointer;
}
button:hover {
opacity: 0.8;
}
#prevBtn {
background-color: #bbbbbb;
}
/* Make circles that indicate the steps of the form: */
.step {
height: 15px;
width: 15px;
margin: 0 2px;
background-color: #bbbbbb;
border: none;
border-radius: 50%;
display: inline-block;
opacity: 0.5;
}
.step.active {
opacity: 1;
}
/* Mark the steps that are finished and valid: */
.step.finish {
background-color: #0000ff;
}
<link href="https://fonts.googleapis.com/css?family=Raleway" rel="stylesheet" />
<span style="font-family: calibri; font-size: 12pt;">
<form id="regForm" style="float: left;">
<h1 style="text-align: left;">Voicemail Troubleshooting</h1>
<!-- One "tab" for each step in the form: -->
<div class="tab">
Is the accurate SKU on the LOS?<br /><br />
Yes <input type="radio" onclick="javascript:yesnoCheck();" name="yesno" id="yesCheck">
No <input type="radio" onclick="javascript:yesnoCheck();" name="yesno" id="noCheck"><br />
</div>
<div class="tab">
Tab 2
<div id="ifNo" style="display: none">
Result of selecting No to first question
</div>
<div id="ifYes" style="display: none"><br /><br />
Can the customer call the VM from their phone?<br /><br />
Yes <input type="radio" onclick="javascript:yesno1Check();" name="yesno1" id="yes1Check">
No <input type="radio" onclick="javascript:yesno1Check();" name="yesno1" id="no1Check"><br />
</div>
</div>
<div class="tab">
Tab 3
<div id="ifYes1" style="display:none"><br />
Result of selecting Yes to second question.
</div>
<div id="ifNo1" style="display:none">
Result of selecting No to second question</div>
</div>
<div style="overflow: auto;">
<div style="float: right;">
<br /><br />
<button type="button" id="prevBtn" onclick="nextPrev(-1)">Previous</button>
<button type="button" id="nextBtn" onclick="nextPrev(1)">Next</button>
</div>
</div>
<!-- Circles which indicates the steps of the form: -->
<div style="text-align: center; margin-top: 40px;">
<span class="step"></span>
<span class="step"></span>
<span class="step"></span>
<span class="step"></span>
</div>
</form>
</span>
I think it what you want -
<link href="https://fonts.googleapis.com/css?family=Raleway" rel="stylesheet" />
<style>
* {
box-sizing: border-box;
}
body {
background-color: #f1f1f1;
}
#regForm {
background-color: #ffffff;
margin: 50px auto;
font-family: calibri;
font-size: 17px
padding: 40px;
width: 30%;
min-width: 300px;
}
h1 {
text-align: center;
}
input {
padding: 10px;
width: 100%;
font-size: 17px;
font-family: Raleway;
border: 1px solid #aaaaaa;
}
/* Mark input boxes that gets an error on validation: */
input.invalid {
background-color: #ffdddd;
}
/* Hide all steps by default: */
.tab {
display: none;
}
button {
background-color: #0000ff;
color: #ffffff;
border: none;
padding: 10px 20px;
font-size: 17px;
font-family: Raleway;
cursor: pointer;
}
button:hover {
opacity: 0.8;
}
#prevBtn {
background-color: #bbbbbb;
}
/* Make circles that indicate the steps of the form: */
.step {
height: 15px;
width: 15px;
margin: 0 2px;
background-color: #bbbbbb;
border: none;
border-radius: 50%;
display: inline-block;
opacity: 0.5;
}
.step.active {
opacity: 1;
}
/* Mark the steps that are finished and valid: */
.step.finish {
background-color: #0000ff;
}
</style>
<span style="font-family: calibri; font-size: 12pt;">
<form id="regForm" style="float: left;">
<h1 style="text-align: left;">Voicemail Troubleshooting</h1>
<!-- One "tab" for each step in the form: -->
<div class="tab">
Is the accurate SKU on the LOS?<br />
<br />
Yes <input type="radio" onclick="javascript:yesnoCheck();" name="yesno" id="yesCheck">
No <input type="radio" onclick="javascript:yesnoCheck();" name="yesno" id="noCheck"><br />
</div>
<div class="tab">Tab 2
<div id="ifNo" style="display:none">
Result of selecting No to first question
</div>
<div id="ifYes" style="display:none"><br />
<br />
Can the customer call the VM from their phone?<br />
<br />
Yes <input type="radio" onclick="javascript:yesno1Check();" name="yesno1" id="yes1Check">
No <input type="radio" onclick="javascript:yesno1Check();" name="yesno1" id="no1Check"><br />
</div>
</div>
<div class="tab">Tab 3
<div id="ifYes1" style="display:none"><br />
Result of selecting Yes to second question.</div>
<div id="ifNo1" style="display:none">
Result of selecting No to second question</div>
</div>
<div style="overflow: auto;">
<div style="float: right;">
<br />
<br />
<button type="button" id="prevBtn" onclick="nextPrev(-1)">Previous</button>
<button type="button" id="nextBtn" onclick="nextPrev(1)">Next</button>
</div>
</div>
<!-- Circles which indicates the steps of the form: -->
<div style="text-align: center; margin-top: 40px;">
<span class="step"></span>
<span class="step"></span>
<span class="step"></span>
<span class="step"></span>
</div>
</form>
</span>
<script>
var currentTab = 0; // Current tab is set to be the first tab (0)
showTab(currentTab); // Display the current tab
function showTab(n) {
// This function will display the specified tab of the form...
var x = document.getElementsByClassName("tab");
x[n].style.display = "block";
//... and fix the Previous/Next buttons:
if (n == 0) {
document.getElementById("prevBtn").style.display = "none";
} else {
document.getElementById("prevBtn").style.display = "inline";
}
if (n == (x.length - 1)) {
document.getElementById("nextBtn").innerHTML = "restart";
document.getElementById("nextBtn").setAttribute('onclick', 'restart()');
} else {
document.getElementById("nextBtn").innerHTML = "Next";
}
//... and run a function that will display the correct step indicator:
fixStepIndicator(n);
}
/* Restart function */
function restart(){
var x = document.getElementsByClassName("tab");
x[x.length - 1].style.display = "none";
document.getElementById("nextBtn").setAttribute('onclick', 'nextPrev(1)');
window.currentTab = 0; // Current tab is set to be the first tab (0)
showTab(window.currentTab); // Display the current tab
}
function nextPrev(n) {
// This function will figure out which tab to display
var x = document.getElementsByClassName("tab");
// Exit the function if any field in the current tab is invalid:
if (n == 1 && !validateForm()) return false;
// Hide the current tab:
x[currentTab].style.display = "none";
// Increase or decrease the current tab by 1:
currentTab = currentTab + n;
// if you have reached the end of the form...
if (currentTab >= x.length) {
// ... the form gets restarted:
document.getElementById("regForm").restart();
return false;
}
// Otherwise, display the correct tab:
showTab(currentTab);
}
function validateForm() {
// This function deals with validation of the form fields
var x, y, i, valid = true;
x = document.getElementsByClassName("tab");
y = x[currentTab].getElementsByTagName("input");
// A loop that checks every input field in the current tab:
for (i = 0; i < y.length; i++) {
// If a field is empty...
if (y[i].value == "") {
// add an "invalid" class to the field:
y[i].className += " invalid";
// and set the current valid status to false
valid = false;
}
}
// If the valid status is true, mark the step as finished and valid:
if (valid) {
document.getElementsByClassName("step")[currentTab].className += " finish";
}
return valid; // return the valid status
}
function fixStepIndicator(n) {
// This function removes the "active" class of all steps...
var i, x = document.getElementsByClassName("step");
for (i = 0; i < x.length; i++) {
x[i].className = x[i].className.replace(" active", "");
}
//... and adds the "active" class on the current step:
x[n].className += " active";
}
</script><script>
function yesnoCheck() {
if (document.getElementById('yesCheck').checked) {
document.getElementById('ifYes').style.display= 'block';
}
else document.getElementById('ifYes').style.display= 'none';
if (document.getElementById('noCheck').checked) {
document.getElementById('ifNo').style.display= 'block';
}
else document.getElementById('ifNo').style.display= 'none';
}</script><script>
function yesno1Check() {
if (document.getElementById('yes1Check').checked) {
document.getElementById('ifYes1').style.display= 'block';
}
else document.getElementById('ifYes1').style.display= 'none';
if (document.getElementById('no1Check').checked) {
document.getElementById('ifNo1').style.display= 'block';
}
else document.getElementById('ifNo1').style.display= 'none';
}
});</script>
Working fiddle - jsfiddle link

Hide a DIV and show another when I press the enter key

I'm trying to do a function that when I press the enter key it disappears a div (containerMessage) and another (containerResult) one appears, what am I doing wrong? When I press the enter key the function is not even called
A Live Example
HTML
<html>
<head>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="bloco">
<h1>NSGM</h1>
<h2>Namorada Super Gostosa e Modelo</h2>
<img src="girlfriend.png">
<div id="containerMessage">
<p id="message">Qual seu nome meu amor</p>
<form>
<input type="text" name="name" id="digitarNome">
</form>
<div id="containerResult">
<p id="result">EU TE AMO RODRIGO</p>
</div>
</div>
</div>
<script src="NSGM.js"></script>
</body>
</html>
Javascript
var digitarNome = document.getElementById("digitarNome");
digitarNome.addEventListener("keydown", function (e) {
if (e.keyCode === 13) {
validate(e);
}
});
function validate(e) {
if (document.getElementById('containerMessage').style.display == 'block') {
document.getElementById('containerMessage').style.display = 'none'
document.getElementById('containerResult').style.display = 'block'
}
}
When you press enter, the form gets submitted, so you'll have to prevent that default behaviour:
var digitarNome = document.getElementById("digitarNome");
digitarNome.addEventListener("keydown", function (e) {
if (e.keyCode === 13) {
e.preventDefault(); // Prevent submitting the form
validate(e);
}
});
The other issue is that you're hiding the containerMessage div which contains your containerResult, so it will never be shown. Check the snippet below, but basically you'll just have to move the containerResult div out of the containerMessage div.
var digitarNome = document.getElementById("digitarNome");
digitarNome.addEventListener("keydown", function(e) {
if (e.keyCode === 13) {
e.preventDefault();
validate(e);
}
});
function validate(e) {
let container = document.getElementById("containerMessage");
if (!container.style.display || container.style.display == "block") {
container.style.display = "none";
document.getElementById("containerResult").style.display = "block";
}
}
body {
background-color: red;
margin: 0;
}
img {
height: 50vh;
}
#bloco {
text-align: center;
margin: 0;
position: absolute;
top: 45%;
left: 50%;
transform: translate(-50%, -50%);
white-space: nowrap;
}
h1 {
margin: 100px 0px 0px 0px;
font-size: 10em;
}
h2 {
margin: 0;
font-size: 3em;
}
p {
font-size: 3em;
margin: 0;
}
h1,
h2,
p {
color: white;
}
input[type="text"] {
margin: 50px 0px 0px 0px;
padding: 16px 20px;
border: none;
border-radius: 8px;
background-color: #f1f1f1;
font-size: 2em;
text-align: center;
}
input[type="text"]:focus {
background-color: #ea8079;
color: white;
outline: 0;
}
#result {
font-size: 6em;
}
#containerResult {
display: none;
}
#containerMessage {
display: block;
}
<div id="bloco">
<h1>NSGM</h1>
<h2>Namorada Super Gostosa e Modelo</h2>
<div id="containerMessage">
<p id="message">Qual seu nome meu amor</p>
<form>
<input type="text" name="name" id="digitarNome" />
</form>
</div>
<div id="containerResult">
<p id="result">EU TE AMO RODRIGO</p>
</div>
</div>
The problem is that .style.display will only return the current style if it has been previously set inline or via javascript.
Otherwise, you must use:
getComputedStyle(element, null).display
where element is previously selected in the DOM.
I removed the form from the example to remove that distraction.
var digitarNome = document.getElementById("digitarNome");
digitarNome.addEventListener("keydown", function(e) {
if (e.keyCode === 13) {
validate(e);
}
});
function validate(e) {
let msgDiv = document.getElementById('containerMessage');
let resDiv = document.getElementById('containerResult');
let divStyle = getComputedStyle(msgDiv, null).display;
if (divStyle == 'block') {
msgDiv.style.display = 'none';
resDiv.style.display = 'block';
}
}
#containerResult{display:none;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<div id="bloco">
<div id="containerMessage">
Nome meu amor: <input type="text" name="name" id="digitarNome">
</div>
<div id="containerResult">
<p id="result">EU TE AMO RODRIGO</p>
</div>
</div>
References:
https://stackoverflow.com/a/4866269/1447509
Element.style will only retrieve the styles from the attribute on the element so
document.getElementById('containerMessage').style.display == 'block'
Will always return false
From W3 schools https://www.w3schools.com/jsref/prop_html_style.asp
Note: The style property only returns the CSS declarations set in the element's inline style attribute, e.g.
. It is not possible to use this property to get information about style rules from the section in the document or external style sheets.
You can instead apply the display style as in line attribute like so
<div id="containerMassage" style="display:block"></div>

Submitting a canvas element in a form

I have managed to get this far from various tutorials and answers posted on other questions but i am now stuck. I have this form
HTML
<!DOCTYPE html>
<html>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://fonts.googleapis.com/css?family=Raleway"
rel="stylesheet">
<link rel="stylesheet" href="style.css">
<body>
<form id="regForm" action="sqlIn.php" method="post">
<h1>Welcome</h1>
<!-- One "tab" for each step in the form: -->
<div class="tab">
<div id="capture"><video id="player" autoplay><canvas id="canvas">
</canvas></video></div>
<script src="camera.js"></script>
<p><input placeholder="First name..." oninput="this.className = ''"
name="fname">
<input placeholder="Last name..." oninput="this.className = ''"
name="lname"></p>
</div>
<!-- One "tab" for each step in the form: -->
<div class="tab">How can we contact you whilst on site?
<p><input placeholder="Phone number" oninput="this.className = ''"
name="Dir_phone"></p>
</div>
<!-- One "tab" for each step in the form: -->
<div class="tab">Who do you work for?
<p><input placeholder="dd" oninput="this.className = ''" name="dd"></p>
</div>
<!-- One "tab" for each step in the form: -->
<div class="tab">Please read our Induction:
<p><input placeholder="Username..." oninput="this.className = ''"
name="uname"></p>
</div>
<!-- One "tab" for each step in the form: -->
<div style="overflow:auto;">
<div style="float:right;">
<button type="button" id="prevBtn"
onclick="nextPrev(-1)">Previous</button>
<button type="button" id="nextBtn" onclick="nextPrev(1)">Next</button>
</div>
</div>
<!-- Circles which indicates the steps of the form: -->
<div style="text-align:center;margin-top:40px;">
<span class="step"></span>
<span class="step"></span>
<span class="step"></span>
<span class="step"></span>
</div>
</form>
<!-- Link to the javascript for form animation/flow -->
<script src="form.js"></script>
</body>
</html>
CSS
'* {
box-sizing: border-box;
}
html {
background: url(wood-is-at-the-heart.jpg) no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
#regForm {
background-color: #ffffff;
margin: 100px auto;
border-radius: 10px;
box-shadow: 4px 4px 3px #245223;
font-family: Raleway;
padding: 40px;
width: 70%;
min-width: 300px;
}
h1 {
text-align: center;
}
input {
padding: 10px;
width: 100%;
font-size: 17px;
font-family: Raleway;
border: 1px solid #aaaaaa;
}
/* Mark input boxes that gets an error on validation: */
input.invalid {
background-color: #ffdddd;
}
/* Hide all steps by default: */
.tab {
display: none;
}
button {
background-color: #4CAF50;
color: #ffffff;
border: none;
padding: 10px 20px;
font-size: 17px;
font-family: Raleway;
cursor: pointer;
}
button:hover {
opacity: 0.8;
}
#prevBtn {
background-color: #bbbbbb;
}
/* Make circles that indicate the steps of the form: */
.step {
height: 15px;
width: 15px;
margin: 0 2px;
background-color: #bbbbbb;
border: none;
border-radius: 50%;
display: inline-block;
opacity: 0.5;
}
.step.active {
opacity: 1;
}
/* Mark the steps that are finished and valid: */
.step.finish {
background-color: #4CAF50;
}
#player{
display: inline-block;
height:400px;
width:500px;
margin: 0px;
}
#capture{
diplay:inline;
padding: 0px;
height:400px;
width:500px;
margin: 0 auto;
}
and Finally JS
var currentTab = 0; // Current tab is set to be the first tab (0)
showTab(currentTab); // Display the crurrent tab
function showTab(n) {
// This function will display the specified tab of the form...
var x = document.getElementsByClassName("tab");
x[n].style.display = "block";
//... and fix the Previous/Next buttons:
if (n == 0) {
document.getElementById("prevBtn").style.display = "none";
} else {
document.getElementById("prevBtn").style.display = "inline";
}
if (n == x.length - 1) {
document.getElementById("nextBtn").innerHTML = "Submit";
} else {
document.getElementById("nextBtn").innerHTML = "Next";
}
//... and run a function that will display the correct step indicator:
fixStepIndicator(n);
}
function nextPrev(n) {
// This function will figure out which tab to display
var x = document.getElementsByClassName("tab");
// Exit the function if any field in the current tab is invalid:
if (n == 1 && !validateForm()) return false;
// Hide the current tab:
x[currentTab].style.display = "none";
// Increase or decrease the current tab by 1:
currentTab = currentTab + n;
// if you have reached the end of the form...
if (currentTab >= x.length) {
// ... the form gets submitted:
document.getElementById("regForm").submit();
return false;
}
// Otherwise, display the correct tab:
showTab(currentTab);
}
function validateForm() {
// This function deals with validation of the form fields
var x,
y,
i,
valid = true;
x = document.getElementsByClassName("tab");
y = x[currentTab].getElementsByTagName("input");
// A loop that checks every input field in the current tab:
for (i = 0; i < y.length; i++) {
// If a field is empty...
if (y[i].value == "") {
// add an "invalid" class to the field:
y[i].className += " invalid";
// and set the current valid status to false
valid = false;
}
}
// If the valid status is true, mark the step as finished and valid:
if (valid) {
document.getElementsByClassName("step")[currentTab].className += "
finish";
}
return valid; // return the valid status
}
function fixStepIndicator(n) {
// This function removes the "active" class of all steps...
var i,
x = document.getElementsByClassName("step");
for (i = 0; i < x.length; i++) {
x[i].className = x[i].className.replace(" active", "");
}
//... and adds the "active" class on the current step:
x[n].className += " active";
}
// and the code to show camera and get the image to a canvas.
const player = document.getElementById('player');
const canvas = document.getElementById('canvas');
const context = canvas.getContext('2d');
const captureButton = document.getElementById('capture');
const constraints = {
video: true,
};
captureButton.addEventListener('click', () => {
context.drawImage(player, 0, 0, canvas.width, canvas.height);
// Stop all video streams.
player.srcObject.getVideoTracks().forEach(track => track.stop());
});
navigator.mediaDevices.getUserMedia(constraints)
.then((stream) => {
// Attach the video stream to the video element and autoplay.
player.srcObject = stream;
});
I have tried various options of putting the canvas image in a variable and then setting a hidden input as that but cannot seem to get anywhere with it? i have all the other elements of the form being submitted by post to a mysql database
Once this is done i will be moving on to form logic and going to questions based on conditions then after that autofill to check if there is already an entry. I am learning as i am going as my previous knowledge comes from before CSS was a thing. You can view it in codepen
See the Pen Web Form by mark (#markarobinson) on CodePen.
I will try my best to answer any questions if more information is needed.
Thank you

Show JavaScript alert in page div rather than pop up box

I have validation functions on a form that currently use alert to display a pop up box with the message:
HTML
<label for="password" >Password:</label>
<input type="password" id="password" name="password" placeholder="password" required>
<label for="password2" >Password:</label>
<input type="password2" id="password2" name="password2" placeholder="confirm assword" required>
<div class="error" id="error"></div>
JS
function confirmPassword() {
var password = document.getElementById("password").value
var password2 = document.getElementById("password2").value
if(password != password2) {
alert('You entered two different passwords, please make sure both password fields match.');
}
}
How can I make the text that currently shows in a pop up box show in the <div class="error" id="error"></div> instead?
Change
alert('You entered two different passwords, please make sure both password fields match.');
to
document.getElementById("error").innerHTML = 'You entered two different passwords, please make sure both password fields match.';
You can change this:
alert('You entered two different passwords, please make sure both password fields match.');
to(as stated by Kevin P.):
document.getElementById("error").innerHTML = "You entered two different passwords, please make sure both password fields match.";
OR using jquery(since you tagged jquery):
$("#error").html("You entered two different passwords, please make sure both password fields match.");
also, to avoid errors please use strict inequality signs:
if(x !== y){
// some code here
}else{
// some code here
}
document.getElementById("error").innerHTML = "You entered two different passwords, please make sure both password fields match.";
You can do something like this:
function showPopup(text, title) {
$('#popup-body').empty();
popup = $('#popup');
popup.css("display", "block");
$('#backdrop-div').css("display", "block");
popupHead = $('#popup-header-text');
popupHead.html(title);
popupBody = $('#popup-body');
popupBody.html(text);
}
function show() {
showPopup($('#text').val(), $('#title').val());
}
(function() {
$('#backdrop-div').click(function() {
$('#popup').css("display", "none");
$('#backdrop-div').css("display", "none");
});
$(document).keyup(function(event) {
if ($('#popup').css("display") == "block") {
if (event.which == 27) {
$('#popup').css("display", "none");
$('#backdrop-div').css("display", "none");
}
}
});
})();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<style>
.popup-box {
position: absolute;
width: 500px;
height: 200px;
top: 50%;
left: 50%;
margin-top: -100px;
margin-left: -250px;
background-color: #FFFFFF;
z-index: 100000000;
border: 2px solid #000000;
border-radius: 15px;
}
.popup-header {
margin-top: -19px;
border-bottom: 2px solid #000000;
background: red;
text-align: center;
font-family: Impact, Charcoal, sans-serif;
border-top-right-radius: 15px;
border-top-left-radius: 15px;
}
.popup-body {
margin-top: 10px;
margin-bottom: 10px;
height: 40px;
background: #FFFFFF;
font-family: Impact, Charcoal, sans-serif;
text-align: center;
}
.popup-header-text {
margin-top: 40px;
}
</style>
<div id="backdrop-div" style="width: 1000%; height: 1000%; z-index: 20000; background-color: #000000; opacity: 0.3; top: 0; left: 0; position: fixed; display: none"></div>
<div id="popup" class="popup-box" style="display: none;">
<div id="popup-header" class="popup-header">
<h3 id="popup-header-text">Header</h3>
</div>
<div id="popup-body" class="popup-body">Text</div>
</div>
<div>
Text:
<textarea id="text">You entered two different passwords, please make sure both password fields match.</textarea>
<br>Title:
<input id="title" value="ERROR!!!">
<br>
<button onclick="show();">Show popup!</button>
</div>
However, instead of copying the code, you may want to change some things, like the CSS.

JavaScript success message after form submit/page re-load

I'm looking for a way to display a simple JS message/pop up when my form has been successfully submitted.
I tried doing this as an 'alert' but it stopped the 'action' from happening (page reloading) and just displayed the message instead.
If I could do this as a js alert after the action has happened and the page has reloaded this would be great but I'm open to suggestions...
Regards,
Marc
function validate() // Required Fields Validation
{
if (document.myForm.Name.value == "") {
alert("Please provide your name");
document.myForm.Name.focus();
return false;
}
if (document.myForm.Company.value == "") {
alert("Please provide your Company name");
document.myForm.Company.focus();
return false;
}
if (document.myForm.Email.value == "") {
alert("Please provide your Email address");
document.myForm.Email.focus();
return false;
}
if (document.myForm.Message.value == "") {
alert("Leave us a message");
document.myForm.Message.focus();
return false;
}
return (true);
}
function validateEmail() // Correct Email Format Validation
{
var emailID = document.myForm.Email.value;
atpos = emailID.indexOf("#");
dotpos = emailID.lastIndexOf(".");
if (atpos < 1 || (dotpos - atpos < 2)) {
alert("Please enter a valid Email address")
document.myForm.Email.focus();
return false;
}
return (true);
}
function nameLength() { // Max Character Validation
x = document.myForm
input = x.Name.value
if (input.length > 40) {
alert("The Name field cannot contain more than 40 characters")
return false
} else {
return true
}
}
function companyLength() {
x = document.myForm
input = x.Company.value
if (input.length > 50) {
alert("The Company field cannot contain more than 50 characters")
return false
} else {
return true
}
}
function emailLength() {
x = document.myForm
input = x.Email.value
if (input.length > 50) {
alert("The Email field cannot contain more than 50 characters")
return false
} else {
return true
}
}
function messageLength() {
x = document.myForm
input = x.Message.value
if (input.length > 300) {
alert("The Message field cannot contain more than 300 characters")
return false
} else {
return true
}
}
#contact-area {
width: 500px;
max-height: 200px;
margin-top: 0px;
float: left;
}
#contact-area input,
#contact-area textarea {
padding: 3px;
width: 520px;
font-family: 'Lato', sans-serif;
font-size: 14px;
margin: 0px 0px 0px 0px;
border: 1px solid #ccc;
}
#contact-area textarea {
height: 90px;
}
#contact-area textarea:focus,
#contact-area input:focus {
border: 1px solid #ffc423;
}
#contact-area input.submit-button {
width: 100px;
float: left;
background-color: #ffc423;
color: black;
margin-top: 13px;
cursor: pointer;
}
#contact-area input.submit-button:hover {
background-color: #002b51;
color: white;
}
label {
float: left;
text-align: left;
margin-right: 15px;
width: 100px;
padding-top: 10px;
padding-bottom: 5px;
font-size: 15px;
color: #ffc423;
font-weight: 700;
}
textarea {
resize: none;
}
<div id="contact-area">
<form method="post" action="contactengine.php" name="myForm" onsubmit="return !!(validate() & validateEmail() & nameLength() & companyLength() & emailLength() & messageLength())">
<label for="Name">Name:</label>
<input type="text" name="Name" id="Name">
<label for="Company">Company:</label>
<input type="text" name="Company" id="Company">
<label for="Email">Email:</label>
<input type="text" name="Email" id="Email">
<label for="Message">Message:</label>
<textarea name="Message" rows="20" cols="20" id="Message" title="Your message | max 300 characters"></textarea>
<input type="submit" name="submit" value="Submit" class="submit-button">
</form>
<div style="clear: both;"></div>
</div>
you can set a value to a querystring param and check this on your page to alert success:
Redirect function update:
if ($success){ print "<meta http-equiv=\"refresh\" content=\"0;URL=contact.html\?success=true">"; } else{ print "<meta http-equiv=\"refresh\" content=\"0;URL=error.htm\">"; }
Your page script:
you can have an on page load function to run the below:
var success = How can I get query string values in JavaScript? ;
if(success != ""){
alert(success); // javascript alert
}

Categories