How to show validation message below each textbox using jQuery? - javascript

I am trying to make a login form in which I have email address and password as the textbox. I have done the validation on the email address part so that it should have proper email address and also on the empty check both for email address and password text box.
Here is my jsfiddle.
As of now, I have added an alert box saying, Invalid if email address and password textbox is empty. Instead of that, I would like to show a simple message just below each text box saying , please enter your email address or password if they are empty?
Just like it has been done here on sitepoint blog.
Is this possible to do in my current HTML form?
Update:-
<body>
<div id="login">
<h2>
<span class="fontawesome-lock"></span>Sign In
</h2>
<form action="login" method="POST">
<fieldset>
<p>
<label for="email">E-mail address</label>
</p>
<p>
<input type="email" id="email" name="email">
</p>
<p>
<label for="password">Password</label>
</p>
<p>
<input type="password" name="password" id="password">
</p>
<p>
<input type="submit" value="Sign In">
</p>
</fieldset>
</form>
</div>
<!-- end login -->
</body>
And my JS -
<script>
$(document).ready(function() {
$('form').on('submit', function (e) {
e.preventDefault();
if (!$('#email').val()) {
if ($("#email").parent().next(".validation").length == 0) // only add if not added
{
$("#email").parent().after("<div class='validation' style='color:red;margin-bottom: 20px;'>Please enter email address</div>");
}
} else {
$("#email").parent().next(".validation").remove(); // remove it
}
if (!$('#password').val()) {
if ($("#password").parent().next(".validation").length == 0) // only add if not added
{
$("#password").parent().after("<div class='validation' style='color:red;margin-bottom: 20px;'>Please enter password</div>");
}
} else {
$("#password").parent().next(".validation").remove(); // remove it
}
});
});
</script>
I am working with JSP and Servlets so as soon as I click Sign In button, it was taking me to another page with valid email and password earlier but now nothing is happening after I click Sign In button with valid email and password.
Any thoughts what could be wrong?

You could put static elements after the fields and show them, or you could inject the validation message dynamically. See the below example for how to inject dynamically.
This example also follows the best practice of setting focus to the blank field so user can easily correct the issue.
Note that you could easily genericize this to work with any label & field (for required fields anyway), instead of my example which specifically codes each validation.
Your fiddle is updated, see here: jsfiddle
The code:
$('form').on('submit', function (e) {
var focusSet = false;
if (!$('#email').val()) {
if ($("#email").parent().next(".validation").length == 0) // only add if not added
{
$("#email").parent().after("<div class='validation' style='color:red;margin-bottom: 20px;'>Please enter email address</div>");
}
e.preventDefault(); // prevent form from POST to server
$('#email').focus();
focusSet = true;
} else {
$("#email").parent().next(".validation").remove(); // remove it
}
if (!$('#password').val()) {
if ($("#password").parent().next(".validation").length == 0) // only add if not added
{
$("#password").parent().after("<div class='validation' style='color:red;margin-bottom: 20px;'>Please enter password</div>");
}
e.preventDefault(); // prevent form from POST to server
if (!focusSet) {
$("#password").focus();
}
} else {
$("#password").parent().next(".validation").remove(); // remove it
}
});
The CSS:
.validation
{
color: red;
margin-bottom: 20px;
}

The way I would do it is to create paragraph tags where you want your error messages with the same class and show them when the data is invalid. Here is my fiddle
if ($('#email').val() == '' || !$('#password').val() == '') {
$('.loginError').show();
return false;
}
I also added the paragraph tags below the email and password inputs
<p class="loginError" style="display:none;">please enter your email address or password.</p>

Here you go:
JS:
$('form').on('submit', function (e) {
e.preventDefault();
if (!$('#email').val())
$('#email').parent().append('<span class="error">Please enter your email address.</span>');
if(!$('#password').val())
$('#password').parent().append('<span class="error">Please enter your password.</span>');
});
CSS:
#charset "utf-8";
/* CSS Document */
/* ---------- FONTAWESOME ---------- */
/* ---------- http://fortawesome.github.com/Font-Awesome/ ---------- */
/* ---------- http://weloveiconfonts.com/ ---------- */
#import url(http://weloveiconfonts.com/api/?family=fontawesome);
/* ---------- ERIC MEYER'S RESET CSS ---------- */
/* ---------- http://meyerweb.com/eric/tools/css/reset/ ---------- */
#import url(http://meyerweb.com/eric/tools/css/reset/reset.css);
/* ---------- FONTAWESOME ---------- */
[class*="fontawesome-"]:before {
font-family: 'FontAwesome', sans-serif;
}
/* ---------- GENERAL ---------- */
body {
background-color: #C0C0C0;
color: #000;
font-family: "Varela Round", Arial, Helvetica, sans-serif;
font-size: 16px;
line-height: 1.5em;
}
input {
border: none;
font-family: inherit;
font-size: inherit;
font-weight: inherit;
line-height: inherit;
-webkit-appearance: none;
}
/* ---------- LOGIN ---------- */
#login {
margin: 50px auto;
width: 400px;
}
#login h2 {
background-color: #f95252;
-webkit-border-radius: 20px 20px 0 0;
-moz-border-radius: 20px 20px 0 0;
border-radius: 20px 20px 0 0;
color: #fff;
font-size: 28px;
padding: 20px 26px;
}
#login h2 span[class*="fontawesome-"] {
margin-right: 14px;
}
#login fieldset {
background-color: #fff;
-webkit-border-radius: 0 0 20px 20px;
-moz-border-radius: 0 0 20px 20px;
border-radius: 0 0 20px 20px;
padding: 20px 26px;
}
#login fieldset div {
color: #777;
margin-bottom: 14px;
}
#login fieldset p:last-child {
margin-bottom: 0;
}
#login fieldset input {
-webkit-border-radius: 3px;
-moz-border-radius: 3px;
border-radius: 3px;
}
#login fieldset .error {
display: block;
color: #FF1000;
font-size: 12px;
}
}
#login fieldset input[type="email"], #login fieldset input[type="password"] {
background-color: #eee;
color: #777;
padding: 4px 10px;
width: 328px;
}
#login fieldset input[type="submit"] {
background-color: #33cc77;
color: #fff;
display: block;
margin: 0 auto;
padding: 4px 0;
width: 100px;
}
#login fieldset input[type="submit"]:hover {
background-color: #28ad63;
}
HTML:
<div id="login">
<h2><span class="fontawesome-lock"></span>Sign In</h2>
<form action="javascript:void(0);" method="POST">
<fieldset>
<div><label for="email">E-mail address</label></div>
<div><input type="email" id="email" /></div>
<div><label for="password">Password</label></div>
<div><input type="password" id="password" /></div> <!-- JS because of IE support; better: placeholder="Email" -->
<div><input type="submit" value="Sign In"></div>
</fieldset>
</form>
And the fiddle: jsfiddle

is only the matter of finding the dom where you want to insert the the text.
DEMO jsfiddle
$().text();

This is the simple solution may work for you.
Check this solution
$('form').on('submit', function (e) {
e.preventDefault();
var emailBox=$("#email");
var passBox=$("#password");
if (!emailBox.val() || !passBox.val()) {
$(".validationText").text("Please Enter Value").show();
}
else if(!IsEmail(emailBox.val()))
{
emailBox.prev().text("Invalid E-mail").show();
}
$("input#email, input#password").focus(function(){
$(this).prev(".validationText").hide();
});});

We will use the jQuery Validation Plugin
we have to include the necessary files in our project. There are two different files to include. The first is the core file, which includes the core features of the plugin, including everything from different validation methods to some custom selectors. The second file contains additional methods to validate inputs like credit card numbers and US-based phone numbers.
You can add these files to your projects via package managers like Bower or NPM.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.min.js"></script>
HTML
<form id="basic-form" action="" method="post">
<p>
<label for="name">Name <span>(required, at least 3 characters)</span></label>
<input id="name" name="name" minlength="3" type="text" required>
</p>
<p>
<label for="email">E-Mail <span>(required)</span></label>
<input id="email" type="email" name="email" required>
</p>
<p>
<input class="submit" type="submit" value="SUBMIT">
</p>
</form>
CSS
body {
margin: 20px 0;
font-family: 'Lato';
font-weight: 300;
font-size: 1.25rem;
width: 300px;
}
form, p {
margin: 20px;
}
p.note {
font-size: 1rem;
color: red;
}
input {
border-radius: 5px;
border: 1px solid #ccc;
padding: 4px;
font-family: 'Lato';
width: 300px;
margin-top: 10px;
}
label {
width: 300px;
font-weight: bold;
display: inline-block;
margin-top: 20px;
}
label span {
font-size: 1rem;
}
label.error {
color: red;
font-size: 1rem;
display: block;
margin-top: 5px;
}
input.error {
border: 1px dashed red;
font-weight: 300;
color: red;
}
[type="submit"], [type="reset"], button, html [type="button"] {
margin-left: 0;
border-radius: 0;
background: black;
color: white;
border: none;
font-weight: 300;
padding: 10px 0;
line-height: 1;
}
Java script
$(document).ready(function() {
$("#basic-form").validate();
});
This is based on the assumption that you have already added the required JavaScript files. Adding those lines of JavaScript will make sure that your form is properly validated and shows all the error messages.

Related

Trying to figure out making a popup window with form in JavaScript, also cookies to remember login attempts for 5 minutes

I have searched around everywhere and no answers to this have shown up.
I am trying to make a login page open up in a popup window, with a fixed size, fitting the form.
You don't need to reprimand me about keeping login info client side, it's just an experiment.
Here's my form, with JS and CSS as well, along with my home page that has a button to redirect to the login and signup pages. (The signup page isn't working yet, and I'll probably ask about how to do that too but that's another thing altogether)
The home page is nowhere near complete obviously.
I just want the page to open the login page as a window, and then people can get redirected to the success.html page with their number in it.
The success pages should also appear in the original window, not the popup.
You also don't need to tell me how awful and crude my coding is, I am new to all this.
Thanks!
(P.S.- If anyone happens to know how to use cookies to make the site remember someone's login attempts for 5 minutes even when/if they close the site that would be awsome!!)
These are my files:
LOGIN PAGE HTML:
var attempt = 3; // Variable to count number of attempts.
// Below function Executes on click of login button.
function validate() {
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
if (username == "Formget" && password == "formget#123") {
alert("Logged in successfully. Welcome, User 1.");
window.location = "success1.html"; // Redirecting to other page.
return false;
} else if (username == "Formget2" && password == "formget#123") {
alert("Logged in successfully. Welcome, User 2.");
window.location = "success2.html"; // Redirecting to other page.
return false;
} else if (username == "Formget3" && password == "formget#123") {
alert("Logged in successfully. Welcome, User 3.");
window.location = "success3.html"; // Redirecting to other page.
return false;
} else {
attempt--; // Decrementing by one.
alert("You have left " + attempt + " attempt(s).");
// Disabling fields after 3 attempts.
if (attempt == 0) {
alert("You have run out of attempts, please try again in 5 minutes.");
document.getElementById("username").disabled = true;
document.getElementById("password").disabled = true;
document.getElementById("submit").disabled = true;
}
}
}
#import url(http://fonts.googleapis.com/css?family=Raleway);
h2 {
background-color: #FEFFED;
padding: 30px 35px;
margin: -10px -50px;
text-align: center;
border-radius: 10px 10px 0 0;
}
hr {
margin: 10px -50px;
border: 0;
border-top: 1px solid #ccc;
margin-bottom: 40px;
}
div.container {
width: 900px;
height: 610px;
margin: 35px auto;
font-family: 'Raleway', sans-serif;
}
div.main {
width: 300px;
padding: 10px 50px 25px;
border: 2px solid gray;
border-radius: 10px;
font-family: 'Audiowide', monospace;
float: left;
margin-top: 50px;
}
input[type=text],
input[type=password] {
width: 100%;
height: 40px;
padding: 5px;
margin-bottom: 25px;
margin-top: 5px;
border: 2px solid #ccc;
color: #4f4f4f;
font-size: 16px;
border-radius: 5px;
}
label {
color: #464646;
text-shadow: 0 1px 0 #fff;
font-size: 14px;
font-weight: bold;
}
center {
font-size: 32px;
}
.note {
color: red;
}
.valid {
color: green;
}
.back {
text-decoration: none;
border: 1px solid rgb(0, 143, 255);
background-color: rgb(0, 214, 255);
padding: 3px 20px;
border-radius: 2px;
color: black;
}
input[type=button] {
font-size: 16px;
background: linear-gradient(#ffbc00 5%, #ffdd7f 100%);
border: 1px solid #e5a900;
color: #4E4D4B;
font-weight: bold;
cursor: pointer;
width: 100%;
border-radius: 5px;
padding: 10px 0;
outline: none;
}
input[type=button]:hover {
background: linear-gradient(#ffdd7f 5%, #ffbc00 100%);
}
<html style="font-family: 'Audiowide', monospace;">
<head>
<title>Log In</title>
<link rel="stylesheet" href="login.css" />
<script src="login.js"></script>
</head>
<body>
<div class="container">
<div class="main">
<h2>Log In</h2>
<form id="form_id" method="post" name="myform">
<label>User Name :</label>
<input type="text" name="username" id="username" />
<label>Password :</label>
<input type="password" name="password" id="password" />
<input type="button" value="Login" id="submit" onclick="validate()" />
</form>
<span></span>
</div>
</div>
</body>
<body onload="checkCookie()"></body>
</html>
HOME PAGE HTML (CSS INSIDE):
a {
border: 1px solid black;
background-color: lightblue;
padding: 5px;
border-radius: 25px;
text-decoration: none;
font-family: 'Audiowide', monospace;
color: black;
}
<b>Log In</b>
<b>Sign In</b>
The files above are as follows, in order:
login
login.css
login.js
home
My goal was to to make the login pop up in a new window and then redirect to each user's specific success page, but instead it opens both a window and a tab with the page, not just a window. The window also is not fixed size.
I also am looking to use cookies for the login attempts, as I said, and any tips on that would also be helpful.

How do I check two fields for identity using an external script like "signup.js"?

I work with Electron.
I have three files in my project.
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="../css/styles.css">
<script src="../js/preload.js"></script>
<script src="../js/signup.js"></script>
</head>
<body>
<form action="" onsubmit="return validate()">
<label for="email"><b>Почта</b></label>
<input type="text" placeholder="Введите почту..." name="email" required>
<label for="psw"><b>Пароль</b></label>
<input type="password" placeholder="Введите пароль..." id="psw" required>
<label for="psw-repeat"><b>Подтверждение пароля</b></label>
<input type="password" placeholder="Повторите пароль..." id="psw-repeat" required>
<hr>
<p id = "terms">Создавая аккаунт, вы соглашаетесь с нашими условиями пользования и приватности.</p>
<button type="submit" class = registerbtn>Зарегистрироваться</button>
</form>
</body>
</html>
styles.css
#import url('https://fonts.googleapis.com/css2?family=Comfortaa:wght#300&display=swap');
#import url('https://fonts.googleapis.com/css2?family=Raleway&display=swap');
body {
font-family: 'Raleway', sans-serif;
}
.sign_up {
padding: 16px;
}
input[type=text],
input[type=password] {
width: 100%;
padding: 15px;
margin: 5px 0 22px 0;
display: inline-block;
border: none;
background: #f1f1f1;
font-family: 'Raleway', sans-serif;
}
hr
{
border: 1px solid #f1f1f1;
margin-bottom: 25px;
}
.registerbtn {
background-color: darkcyan;
color: white;
padding: 16px 20px;
margin: 8px 0;
border: none;
cursor: pointer;
width: 100%;
opacity: 0.9;
}
.registerbtn:hover {
opacity: 1;
}
a {
color: dodgerblue;
}
#warning {
color: crimson;
}
signup.js
function validate()
{
var password = document.getElementById(psw).value;
var password_repeat = document.getElementById(psw-repeat).value
if(password != password_repeat)
{
document.getElementById(psw).insertAdjacentHTML("afterend", "<p id = \"warning\">Пароли не совпадают!</p>")
}
}
The project itself is written in Russian. I want to use the file signup.js to check the identity of the fields "psw" and "psw-repeat", but when the program runs, nothing happens. As for the content of the fields, they are emptied when the button is clicked.
The onsubmit value should only have method call, not with "return".
So, I suggest you to use something like this:
onsubmit="validate()"
Documentation
Also, the submit button have issue with "class" css, it should look like this:
<button type="submit" class="register btn">Зарегистрироваться</button>

how do I use one script for multiple buttons/links?

this is gonna be probably a basic thing to answer too as I'm learning to code html/css/js and to do so I'm building a random website for a company that doesn't even know I exist.
So I have built a side nav menu with LINKS ()that show modal windows on-click so that the website remains a one-page website and one of those is a "ask an estimate" form that so far send info to nowhere (I will learn that later on).
Now, on the main page, I have made a series of hero banners to display their products and on each one of them I want to add a "ask an estimate" BUTTON () that show the same modal window as the link in the side nav. (probably will do the same with the contact link on one of those banners)
Now this is the code I'm using (most of it from w3):
Javascript file:
var modalPreventivo = document.getElementById("modalPreventivo");
var btnPreventivo = document.getElementById("btnPreventivo");
var spanPreventivo = document.getElementsByClassName("closePreventivo")[0];
btnPreventivo.onclick=function() {
modalPreventivo.style.display= "block";
}
spanPreventivo.onclick = function() {
modalPreventivo.style.display = "none";
}
windowPreventivo.onclick = function(eventPreventivo) {
if (eventPreventivo.target == modalPreventivo) {
modalPreventivo.style.display = "none";
}
}
HTML on the link (works good Preventivo=Estimate)
<li>Preventivo</li>
<div id="modalPreventivo" class="modalPreventivo">
<div class="modal-contentPreventivo">
<div class="container">
<span class="closePreventivo">×</span>
<h1>Chiedi ora il tuo preventivo gratuitamente e senza impegno!</h1><br>
<form action="/action_page.php">
<label for="fname">Nome</label><br>
<input type="text" id="fname" name="firstname" placeholder="Il tuo nome">
<br>
<label for="lname">Cognome</label><br>
<input type="text" id="lname" name="lastname" placeholder="Il tuo cognome">
<br>
<label for="country">E-mail (solo per ricontattarvi no spam)</label><br>
<input type="text" id="Email" name="email" placeholder="Il tuo indirizzo di posta elettronica">
<br>
<label for="subject">Come possiamo aiutarvi?</label><br>
<textarea id="subject" name="subject" placeholder="Scrivici i dettagli della tua richiesta!" style="height:200px"></textarea>
<br>
<input type="submit" value="Richiedi ora!">
</form>
</div>
</div>
</div>
<script src="/Odorici/Javascript/preventivo.js"></script>
HTML button on hero banner (doesn't work at all)
<div class="hero-image" style="background-image: url(/Odorici/img/sliding\ gate.jpg);">
<div class="hero-text">
<h1>Cancelli Carrai</h1>
<p>Produciamo:
<ul>
<li>Cancelli carrai scorrevoli ciechi</li>
<li>Cancelli carrai scorrevoli normali</li>
<li>Cancelli carrai ad anta ciechi</li>
<li>Cancelli carrai ad anta normali in ferro</li>
</ul>
Su misura e con la possibilità di verniciatura e zincatura a caldo.</p>
<button type="button" id="btnPreventivo" >Richiedi Preventivo</button>
</div>
</div>
I forgot to put the CSS (thanks KEN!)
.modalPreventivo {
display:none; /* Hidden by default */
position:fixed; /* Stay in place */
z-index: 1; /* Sit on top */
padding-top: 50px; /* Location of the box */
left: 0;
top: 0;
width: 100%; /* Full width */
height: 100%; /* Full height */
overflow: auto; /* Enable scroll if needed */
background-color: rgb(0,0,0); /* Fallback color */
background-color: rgba(0,0,0,0.5); /* Black w/ opacity */
float: center;
}
/* Modal Content */
.modal-contentPreventivo {
display: block;
background-color: wheat;
color:goldenrod;
margin: auto;
padding: 10px 20px 10px 20px;
border: 1px solid #111;
border-radius: 5px;
width: fit-content;
}
/* The Close Button */
.closePreventivo {
color: #aaa;
float: right;
font-size: 35px;
font-weight: bold;
}
.closePreventivo:hover,
.closePreventivo:focus {
color: black;
text-decoration: none;
cursor: pointer;
}
input[type=text], select, textarea {
width: 100%;
padding: 8px;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
margin-top: 6px;
margin-bottom: 16px;
resize: vertical;
}
input[type=submit] {
background-color: goldenrod;
color: #7a1818;
padding: 12px 20px;
border: 1px solid #111;
border-radius: 4px;
cursor: pointer;
font-weight: bold;
}
input[type=submit]:hover {
background-color: rgb(16, 172, 16);
color: goldenrod;
font-weight: bold;
}
In the beginning, I thought that using the same ID would have work (also because while building the menu the "contacts" link has been showing the "estimate" form instead of its own "contact" modal window, but it won't work.
I tried to copy and paste the whole code from the "estimate" LINK with all the boxes and the and it won't work, I tried changing id, using href #preventivo, but I feel like nothing works cause I'm probably using the wrong functions or maybe I'm coding something wrong in the ... I can't figure it out!
When I google this problem I read many articles that use Jquery (?) but I feel this should be much easier since when I didn't want this modal showing on the wrong link on the menu, it would have kept showing up (and it took me a while to fix that!) but now that I want it to show up on several links/buttons it won't...

my html form on submitting is not calling the function password validation is there anything wrong with the code?

<html>
<script>
function passwordvalidation() #validate if password is strong and if botth passwords are equal
{
var x=document.forms["signup"]["psw"].value;
var y=document.form["signup"]["psw-repeat"].value;
var z=document.form["signup"]["email"].value;
alert(x);
if (x == ""||y==""||z=="") {
alert("form must be filled out");
return false;
}
else if(y!=x)
{
alert("password does not match");
return false;
}
else if (!(x.match(/[a-z]/g) && x.match(
/[A-Z]/g) && x.match(
/[0-9]/g) && x.match(
/[^a-zA-Z\d]/g) && x.length >= 8))
{
alert("weak password")
return false;
}
else
{
return true;
}
}
</script>
<style>
body {font-family: Arial, Helvetica, sans-serif;}
* {box-sizing: border-box}
/* Full-width input fields */
input[type=text], input[type=password] {
width: 100%;
padding: 15px;
margin: 5px 0 22px 0;
display: inline-block;
border: none;
background: #f1f1f1;
}
input[type=text]:focus, input[type=password]:focus {
background-color: #ddd;
outline: none;
}
hr {
border: 1px solid #f1f1f1;
margin-bottom: 25px;
}
/* Set a style for all buttons */
button {
background-color: #4CAF50;
color: white;
padding: 14px 20px;
margin: 8px 0;
border: none;
cursor: pointer;
width: 100%;
opacity: 0.9;
}
button:hover {
opacity:1;
}
/* Extra styles for the cancel button */
.cancelbtn {
padding: 14px 20px;
background-color: #f44336;
}
/* Float cancel and signup buttons and add an equal width */
.cancelbtn, .signupbtn {
float: left;
width: 50%;
}
/* Add padding to container elements */
.container {
padding: 16px;
}
/* Clear floats */
.clearfix::after {
content: "";
clear: both;
display: table;
}
/* Change styles for cancel button and signup button on extra small screens */
#media screen and (max-width: 300px) {
.cancelbtn, .signupbtn {
width: 100%;
}
}
</style>
<body>
<form name="signup" action="/login" onsubmit="return passwordvalidation()" style="border:1px solid #ccc">
<div class="container">
<h1>Sign Up</h1>
<h6>Please fill in this form to create an account.</h6>
<p>Strong password must contain 8 characters </p>
<hr>
<label for="email"><b>Email</b></label>
<input type="text" placeholder="Enter Email" name="email" required>
<label for="psw"><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="psw" required>
<label for="psw-repeat"><b>Repeat Password</b></label>
<input type="password" placeholder="Repeat Password" name="psw-repeat" required>
<div class="clearfix">
<button type="submit" class="signupbtn">Sign Up</button>
</div>
</div>
</form>
</body>
</html>
You have several errors in these lines:
var x=document.forms["signup"]["psw"].value;
var y=document.form["signup"]["psw-repeat"].value;
var z=document.form["signup"]["email"].value;
You can use many methods to retrieve the inputs values, but this way is throwing errors. Check how to do it by using document.getElementBy*** or similar
It is calling the validation function, but you made a spelling mistake in second and third line. Correct
document.form --> document.forms document.form is undefined and your function is exiting with TypeError when you call document.form["signup"] without returning false, and thus your form is navigating to defined action
function passwordvalidation(form)
{
var x=form["psw"].value;
var y=form["psw-repeat"].value;
var z=form["email"].value;
if (x == ""||y==""||z=="") {
alert("form must be filled out");
console.log("form must be filled out");
return false;
}
else if(y!=x)
{
alert("password does not match");
return false;
}
else if (!(x.match(/[a-z]/g) && x.match(
/[A-Z]/g) && x.match(
/[0-9]/g) && x.match(
/[^a-zA-Z\d]/g) && x.length >= 8))
{
alert("weak password")
return false;
}
else
{
return true;
}
}
body {font-family: Arial, Helvetica, sans-serif;}
* {box-sizing: border-box}
/* Full-width input fields */
input[type=text], input[type=password] {
width: 100%;
padding: 15px;
margin: 5px 0 22px 0;
display: inline-block;
border: none;
background: #f1f1f1;
}
input[type=text]:focus, input[type=password]:focus {
background-color: #ddd;
outline: none;
}
hr {
border: 1px solid #f1f1f1;
margin-bottom: 25px;
}
/* Set a style for all buttons */
button {
background-color: #4CAF50;
color: white;
padding: 14px 20px;
margin: 8px 0;
border: none;
cursor: pointer;
width: 100%;
opacity: 0.9;
}
button:hover {
opacity:1;
}
/* Extra styles for the cancel button */
.cancelbtn {
padding: 14px 20px;
background-color: #f44336;
}
/* Float cancel and signup buttons and add an equal width */
.cancelbtn, .signupbtn {
float: left;
width: 50%;
}
/* Add padding to container elements */
.container {
padding: 16px;
}
/* Clear floats */
.clearfix::after {
content: "";
clear: both;
display: table;
}
/* Change styles for cancel button and signup button on extra small screens */
#media screen and (max-width: 300px) {
.cancelbtn, .signupbtn {
width: 100%;
}
}
<form name="signup" action="/login" onsubmit="return passwordvalidation(this)" style="border:1px solid #ccc">
<div class="container">
<h1>Sign Up</h1>
<h6>Please fill in this form to create an account.</h6>
<p>Strong password must contain 8 characters </p>
<hr>
<label for="email"><b>Email</b></label>
<input type="text" placeholder="Enter Email" name="email" required>
<label for="psw"><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="psw" required>
<label for="psw-repeat"><b>Repeat Password</b></label>
<input type="password" placeholder="Repeat Password" name="psw-repeat" required>
<div class="clearfix">
<button type="submit"class="signupbtn">Sign Up</button>
</div>
</div>
</form>

jQuery load modal after an interval only one time per session

I would like to show a modal after 5 seconds, but only once per session (website visit).
This is what I have so far:
$(document).ready(function ()
{
//Fade in delay for the background overlay (control timing here)
$("#bkgOverlay").delay(4800).fadeIn(400);
//Fade in delay for the popup (control timing here)
$("#delayedPopup").delay(5000).fadeIn(400);
//Hide dialouge and background when the user clicks the close button
$("#btnClose").click(function (e)
{
HideDialog();
e.preventDefault();
});
});
//Controls how the modal popup is closed with the close button
function HideDialog()
{
$("#bkgOverlay").fadeOut(400);
$("#delayedPopup").fadeOut(300);
}
This is the codepen for it:
https://codepen.io/uxfed/pen/BmyeEr
I would like this modal to only show one time per website session.
You can put your fading code into body of if statement. I did it via localStorage tool. This code works for me:
$(function(){
console.log(window.localStorage);
var ip_s = localStorage.getItem('ip');
var d = new Date();
!ip_s ? use_local_storage(d) : console.log('not the first visit');
})
function use_local_storage(d) {
$.getJSON('https://api.ipify.org?format=jsonp&callback=?', function(data) {
var iip = String(JSON.parse(JSON.stringify(data, null, 2)).ip);
localStorage.setItem('ip', iip);
localStorage.setItem('day_visit', d.toLocaleDateString());
console.log(window.localStorage);
// load your function here
// question_body();
});
}
Code in Snippet doesn't works here, but in your project it would.
function hideDialog(){
$("#bkgOverlay").fadeOut(400);
$("#delayedPopup").fadeOut(300);
}
function question_body(){
//Fade in delay for the background overlay (control timing here)
$("#bkgOverlay").delay(4800).fadeIn(400);
//Fade in delay for the popup (control timing here)
$("#delayedPopup").delay(5000).fadeIn(400);
//Hide dialouge and background when the user clicks the close button
$("#btnClose").click(function (e){
HideDialog();
e.preventDefault();
});
}
$(function(){
console.log(window.localStorage);
var ip_s = localStorage.getItem('ip');
var d = new Date();
!ip_s ? use_local_storage(d) : console.log('not the first visit');
})
function use_local_storage(d) {
$.getJSON('https://api.ipify.org?format=jsonp&callback=?', function(data) {
var iip = String(JSON.parse(JSON.stringify(data, null, 2)).ip);
localStorage.setItem('ip', iip);
localStorage.setItem('day_visit', d.toLocaleDateString());
console.log(window.localStorage);
// load your function here
// question_body();
});
}
.instructions {
text-align:center;
font-size:20px;
margin: 15vh;
}
/* //////////////////////////////////////////////////////////////////////////////////////////////
// Default Modal Styles //
////////////////////////////////////////////////////////////////////////////////////////////// */
/* This is the background overlay */
.backgroundOverlay {
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
height: 100%;
width: 100%;
margin: 0;
padding: 0;
background: #000000;
opacity: .85;
filter: alpha(opacity=85);
-moz-opacity: .85;
z-index: 101;
display: none;
}
/* This is the Popup Window */
.delayedPopupWindow {
display: none;
position: fixed;
width: auto;
max-width: 480px;
height: 310px;
top: 50%;
left: 50%;
margin-left: -260px;
margin-top: -180px;
background-color: #efefef;
border: 2px solid #333;
z-index: 102;
padding: 10px 20px;
}
/* This is the closing button */
#btnClose {
width:100%;
display: block;
text-align: right;
text-decoration: none;
color: #BCBCBC;
}
/* This is the closing button hover state */
#btnClose:hover {
color: #c90c12;
}
/* This is the description headline and paragraph for the form */
#delayedPopup > div.formDescription {
float: left;
display: block;
width: 44%;
padding: 1% 3%;
font-size: 18px;
color: #666;
clear: left;
}
/* This is the styling for the form's headline */
#delayedPopup > div.formDescription h2 {
color: #444444;
font-size: 36px;
line-height: 40px;
}
/*
////////// MailChimp Signup Form //////////////////////////////
*/
/* This is the signup form body */
#delayedPopup #mc_embed_signup {
float: left;
width: 47%;
padding: 1%;
display: block;
font-size: 16px;
color: #666;
margin-left: 1%;
}
/* This is the styling for the signup form inputs */
#delayedPopup #mc-embedded-subscribe-form input {
width: 95%;
height: 30px;
font-size: 18px;
padding: 3px;
margin-bottom: 5px;
}
/* This is the styling for the signup form inputs when they are being hovered with the mouse */
#delayedPopup #mc-embedded-subscribe-form input:hover {
border:solid 2px #40c348;
box-shadow: 0 1px 3px #AAAAAA;
}
/* This is the styling for the signup form inputs when they are focused */
#delayedPopup #mc-embedded-subscribe-form input:focus {
border:solid 2px #40c348;
box-shadow: none;
}
/* This is the styling for the signup form submit button */
#delayedPopup #mc-embedded-subscribe {
width: 100%!important;
height: 40px!important;
margin: 10px auto 0 auto;
background: #5D9E62;
border: none;
color: #fff;
}
/* This is the styling for the signup form submit button hover state */
#delayedPopup #mc-embedded-subscribe:hover {
background: #40c348;
color: #fff;
box-shadow:none!important;
cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="instructions">Wait for 5 seconds</div>
<div id="bkgOverlay" class="backgroundOverlay"></div>
<div id="delayedPopup" class="delayedPopupWindow">
<!-- This is the close button -->
[ X ]
<!-- This is the left side of the popup for the description -->
<div class="formDescription">
<h2>Sign Up and <span style="color: #40c348; font-weight: bold;">Save $25!</span></h2>
<p>Sign up for our Deal Alerts and save
$25 Off of your first order of $50 or more!</p>
</div>
<!-- Begin MailChimp Signup Form -->
<div id="mc_embed_signup">
<form action="" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate="">
<div class="mc-field-group">
<label for="mce-FNAME">First Name
<span class="asterisk">*</span>
</label>
<input type="text" value="" name="FNAME" class="" id="mce-FNAME">
</div>
<div class="mc-field-group">
<label for="mce-LNAME">Last Name
<span class="asterisk">*</span>
</label>
<input type="text" value="" name="LNAME" class="" id="mce-LNAME">
</div>
<div class="mc-field-group">
<label for="mce-EMAIL">Email Address
<span class="asterisk">*</span>
</label>
<input type="email" value="" name="EMAIL" class="required email" id="mce-EMAIL">
</div>
<div id="mce-responses" class="clear">
<div class="response" id="mce-error-response" style="display:none"></div>
<div class="response" id="mce-success-response" style="display:none"></div>
</div>
<!-- real people should not fill this in and expect good things - do not remove this or risk form bot signups-->
<div style="position: absolute; left: -5000px;">
<input type="text" name="b_2aabb98e55b83ba9d3bd551f5_e6c08b53b4" value="">
</div>
<div class="clear">
<input type="submit" value="Save Money!" name="subscribe" id="mc-embedded-subscribe" class="button">
</div>
</form>
</div>
<!-- End MailChimp Signup Form -->
</div>

Categories