I have been trying to get this to work for a while now. I cannot connect the login function to the form.
I have tried onsubmit on both the form tag and the button input tag, i have tried onclick but it does not get the code from js function.
index1.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Google maps</title>
<meta name="viewport" content="initial-scale=1.0">
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<!--<link rel="http://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">-->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="util.js"></script>
<script src="JavaScript.js"></script>
<script type="text/javascript"></script>
<style>
#container {
width: 1200px;
}
#map {
width: 80%;
min-height: 600px;
/*float: right;*/
margin-top: 15px;
margin-left: auto;
margin-right: auto;
}
#img {
width: 150px;
height: 150px;
float: left;
margin-top: auto;
}
/*sökruta*/
#searchBox {
background-color: #ffffff;
padding: 5px;
font-family: 'Roboto','sans-serif';
margin-bottom: 10px;
float: top;
}
/*
html, body {
height: 100%;
margin: 0;
padding: 0;
}
*/
.search-form .form-group {
float: right !important;
transition: all 0.35s, border-radius 0s;
width: 32px;
height: 32px;
background-color: #fff;
box-shadow: 0 1px 1px rgba(0, 0, 0, 0.075) inset;
border-radius: 25px;
border: 1px solid #ccc;
}
.search-form .form-group input.form-control {
padding-right: 20px;
border: 0 none;
background: transparent;
box-shadow: none;
display:block;
}
.search-form .form-group input.form-control::-webkit-input-placeholder {
display: none;
}
.search-form .form-group input.form-control:-moz-placeholder {
/* Firefox 18- */
display: none;
}
.search-form .form-group input.form-control::-moz-placeholder {
/* Firefox 19+ */
display: none;
}
.search-form .form-group input.form-control:-ms-input-placeholder {
display: none;
}
.search-form .form-group:hover,
.search-form .form-group.hover {
width: 100%;
border-radius: 4px 25px 25px 4px;
}
.search-form .form-group span.form-control-feedback {
position: absolute;
top: -1px;
right: -2px;
z-index: 2;
display: block;
width: 34px;
height: 34px;
line-height: 34px;
text-align: center;
color: #3596e0;
left: initial;
font-size: 14px;
}
.form-group {
max-width: 300px;
margin-right: auto;
margin-left: auto;
}
</style>
</head>
<body id="container">
<img id="img" src="http://www2.math.su.se/icsim/images/sterik.jpg" alt="Stockholm"/>
<div class="row">
<br>
<div class="col-md-4 col-md-offset-3">
<form action="" class="search-form">
<div class="form-group has-feedback">
<label id="Search" class="sr-only">Search</label>
<input type="text" class="form-control" name="search" id="searchField" placeholder="Sök">
<span class="glyphicon glyphicon-search form-control-feedback"></span>
</div>
</form>
</div>
<div class="form-group">
<form id="loginForm" name="loginForm" method="POST">
<label for="user">Användarnamn: </label>
<br>
<input class="form-control" type="text" id="user" name="user" required>
<br>
<label for="password">Lösenord: </label>
<br>
<input class="form-control" type="password" id="password" name="passwords" required>
<br>
<br>
<input class="form-control" type="submit" id="login" value="Logga in" onclick="login()">
</form>
</div>
<div id="map">
</div>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDNPkC40KP9lMKHUsJW7q403qnwRqYkTno&callback=initMap">
</script>
</div>
</body>
JavaScript.js
function login() {
//spara username och password i två varibler med samma namn från formet.
var username = document.getElementById("user").value;
var password = document.getElementById("password").value;
if(username === "admin"
&& password === "123" )
{
alert( "validation succeeded" );
location.href="adminView.php";
}
else
{
alert( "validation failed" );
location.href="index1.html";
}
}
I have created working JSFiddle - Please Check : https://jsfiddle.net/5w6fg52m/1/
Below Code working fine :
<script>
//just change function name as it's conflict with button id
function login1() {
//spara username och password i två varibler med samma namn från formet.
var username = document.getElementById("user").value;
var password = document.getElementById("password").value;
if(username === "admin"
&& password === "123" )
{
alert( "validation succeeded" );
location.href="adminView.php";
}
else
{
alert( "validation failed" );
location.href="index1.html";
}
return false;
}
</script>
//HTML
<div class="form-group">
<form id="loginForm" name="loginForm" method="POST">
<label for="user">Användarnamn: </label>
<br>
<input class="form-control" type="text" id="user" name="user" required>
<br>
<label for="password">Lösenord: </label>
<br>
<input class="form-control" type="password" id="password" name="passwords" required>
<br>
<br>
<input class="form-control" type="button" id="login" value="Logga in" onclick="return login1();">
</form>
</div>
-> I have created other version of JSFiddle, so you come to know conflict issue easily: https://jsfiddle.net/5w6fg52m/2/
Here i have keep function name same(login) and change ID of submit button.
You can set the submit event directly to your like
document.getElementById("loginForm").onsubmit = function() { ... };
Bellow a sample snippet :
window.onload = function(){
document.getElementById("loginForm").onsubmit = function() {
//spara username och password i två varibler med samma namn från formet.
var username = document.getElementById("user").value;
var password = document.getElementById("password").value;
if (username === "admin" &&
password === "123") {
alert("validation succeeded");
//location.href = "adminView.php";
} else {
alert("validation failed");
//location.href = "index1.html";
}
// to prevent submit
return false;
}
}
<div class="form-group">
<form id="loginForm" name="loginForm" method="POST">
<label for="user">Användarnamn: </label>
<br>
<input class="form-control" type="text" id="user" name="user" required>
<br>
<label for="password">Lösenord: </label>
<br>
<input class="form-control" type="password" id="password" name="passwords" required>
<br>
<br>
<input class="form-control" type="submit" id="login" value="Logga in">
</form>
</div>
This happens when you declare variable or function with the same name as declare before. just rename login function or rename id="login".
Related
I am trying to build a form and do some validation using JS. On success I want to redirect it to some other page in the same directory. While running window.location.href over console it is working...but while submitting form, it is not working.
Can someone please help me in this.
My code is:
<html>
<head>
<style>
body {font-family: Arial, Helvetica, sans-serif;}
input[type=text], input[type=password] {
width: 100%;
padding: 12px 20px;
margin: 8px 0;
display: inline-block;
border: 1px solid #ccc;
box-sizing: border-box;
}
button {
background-color: #4CAF50;
color: white;
padding: 14px 20px;
margin: 8px 0;
border: none;
cursor: pointer;
width: 100%;
}
button:hover {
opacity: 0.8;
}
.container {
padding: 16px;
width: 400px;
align-self: center;
}
span.psw {
padding-top: 16px;
}
</style>
<title>Login Page</title>
</head>
<body style="text-align: center;">
<h2 style="text-align: center;">The Mega Cart</h2>
<form name=loginForm onsubmit="login()" style="display: inline-block;">
<div class="container" style="text-align: center;">
<label for="uname"><b>Username</b></label>
<input type="text" placeholder="Enter Username" name="uname" required>
<label for="psw"><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="psw" required>
<button type="submit">Login</button>
</div>
<span class="psw">New user Sign up here. Sign Up</span>
</div>
</form>
</body>
<script>
function login() {
let uname = document.forms["loginForm"]["uname"].value;
let pwd = document.forms["loginForm"]["psw"].value;
window.location.href="main.html";
return false;
}
</script>
</html>
I have already checked that this login function is called.
When you click on the form submit button it call the function login in javascript. In which you have write down the code to redirect the page.
You forgot to prevent the form to submit and that is why you are redirecting to the same page with filled-up values.
If you want to submit your form to specific URL then you should add the action attribute to the form like below.
<form name=loginForm action="URL on which you want to submit form" onsubmit="login()" style="display: inline-block;">
If you want to redirect from the login() function then you should pass the event as an argument from the form and then prevent form submission from the login() function. Please check the below code.
In your form: <form name=loginForm onsubmit="login(event)" style="display: inline-block;">
Change Login function:
function login(e) {
e.preventDefault();
let uname = document.forms["loginForm"]["uname"].value;
let pwd = document.forms["loginForm"]["psw"].value;
window.location.href="main.html";
}
NOTE! Don't forget to pass event in login function
Try this:
window.location.replace('main.html');
In onsubmit function, you can't redirect the page
First, In your form tag, add an action attribute
<form name=loginForm onsubmit="login()" action="main.html" style="display: inline-block;">
Second, Fixed your login function
function login() {
let uname = document.forms["loginForm"]["uname"].value;
let pwd = document.forms["loginForm"]["psw"].value;
return false;
}
Check the redirect URL that contains your data
Try This:
<html>
<head>
<style>
body {font-family: Arial, Helvetica, sans-serif;}
input[type=text], input[type=password] {
width: 100%;
padding: 12px 20px;
margin: 8px 0;
display: inline-block;
border: 1px solid #ccc;
box-sizing: border-box;
}
button {
background-color: #4CAF50;
color: white;
padding: 14px 20px;
margin: 8px 0;
border: none;
cursor: pointer;
width: 100%;
}
button:hover {
opacity: 0.8;
}
.container {
padding: 16px;
width: 400px;
align-self: center;
}
span.psw {
padding-top: 16px;
}
</style>
<title>Login Page</title>
</head>
<body style="text-align: center;">
<h2 style="text-align: center;">The Mega Cart</h2>
<form name=loginForm onsubmit="login()" style="display: inline-block;">
<div class="container" style="text-align: center;">
<label for="uname"><b>Username</b></label>
<input type="text" placeholder="Enter Username" name="uname" required>
<label for="psw"><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="psw" required>
<button type="button" onclick="login()">Login</button>
</div>
<span class="psw">New user Sign up here. Sign Up</span>
</div>
</form>
</body>
<script>
function login() {
let uname = document.forms["loginForm"]["uname"].value;
let pwd = document.forms["loginForm"]["psw"].value;
window.location.href = "https://minisoft.com.bd/";
return false;
}
</script>
</html>
JS newbie here. I have been trying to learn basic front end on my own and tried to create this form validation but my error messages are not working properly. If a field is empty I want each field to return their own error message but somethings are overwriting others.
Attaching the codes and the screenshot.
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Form Validator</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="container">
<form id="all-form" action="">
<h3>Register with us</h3>
<div class="form-control">
<label for="Username">Username</label>
<input id="user" type="username" placeholder="Enter Username" />
<small>error message</small>
</div>
<div class="form-control">
<label for="email">Email</label>
<input id="mail" type="email" placeholder="Enter Email" />
<small>error message</small>
</div>
<div class="form-control">
<label for="password">Password</label>
<input id="pass" type="password" placeholder="Enter Password" />
<small>error message</small>
</div>
<div class="form-control">
<label for="password">Confirm Password</label>
<input id="pass-again" type="password" placeholder="Enter Password Again" />
<small>error message</small>
</div>
<button type="submit" class="submit-btn">Submit</button>
</div>
</form>
<script src="app.js"></script>
</body>
</html>
:root{
--success-color:#2ecc71;
--error-color:#e74c3c;
}
*{
margin:0px;
padding: 0px;
box-sizing: border-box;
font-family: Arial, Helvetica, sans-serif;
}
.container{
position: relative;
top:10em;
margin: auto;
background-color: #fff;
width: 400px;
border-radius: 5px;
box-shadow:0 2px 10px rgba(0,0,0, 0.3);
}
form{
padding:20px 20px;
}
h3 {
text-align: center;
}
label, input{
display: block;
margin:5px;
width: 90%;
}
label{
padding-top: 15px;
padding-right: 15px;
text-align: left;
margin-bottom: 5px;
}
input{
padding:3px;
border-radius: 5%;
font-size: 14px;
}
.submit-btn{
display: block;
padding:10px;
background-color: royalblue;
color: white;
cursor: pointer;
border-radius: 4px;
font-size: 16px;
margin-top:20px;
width: 100%;
}
input:focus{
outline:0;
border-color: #777;
}
.form-control.success input{
border-color: var(--success-color);
}
.form-control.error input{
border-color: var(--error-color);
}
.form-control small{
color:var(--error-color);
position: relative;
bottom:1px;
left:7px;
visibility: hidden;
}
.form-control.error small{
visibility: visible;
}
// Selectors
const username = document.querySelector("#user");
const mail = document.querySelector("#mail");
const pass = document.querySelector("#pass");
const passAgain= document.querySelector("#pass-again");
const sbtBtn = document.querySelector(".submit-btn");
const form = document.querySelector("#all-form");
// Event Listeners
function showError(input,message){
const formControl = input.parentElement;
formControl.className = "form-control error";
const small = document.querySelector("small");
small.innerText = message;
}
function showSuccess(input){
const formControl = input.parentElement;
formControl.className = "form-control success";
}
form.addEventListener("submit",checkAll);
function checkAll(e){
e.preventDefault();
if(username.value === ""){
showError(username, "Username is required");
} else {
showSuccess(username);
}
if(mail.value === ""){
showError(mail, "E-mail is required");
} else {
showSuccess(mail);
}
if(pass.value === ""){
showError(pass, "Password is required");
} else {
showSuccess(pass);
}
if(passAgain.value === ""){
showError(passAgain, "Enter password again please");
} else {
showSuccess(passAgain);
}
}
I'm having difficulty implementing localStorage on my site (https://www.reclaimdesign.org).
What I am trying to do is:
Newsletter subscription pop-up on each page - this works fine
Click X to close the subscription pop-up - this also works fine
Remember the closed state of the window so that all other pages visited on our site don't have the pop-up and irritate the user after they have closed the pop-up already - this is not working. Not even a little bit.
My thinking was to set a variable with localStorage and then refer to the variable to see if the windows should be displayed or not. It is highly likely that my logic and syntax are at best sketchy, so if anyone could please guide me in the correct method this would be much appreciated.
The code I have been tinkering with for the subscription pop-up looks like this:
<script>
function setSignup(val) {
localStorage.setItem("popState", val);
}
function getSignup() {
$(window).on("load", function() {
if(localStorage.getItem("popState") == 'hide'){
//$(".signup").hide();
$(".signup").css("display", "none");
}
else if (localStorage.getItem("popState") != 'hide'){
$(".signup").css("display", "block");
}
});
}
</script>
<div class="signup">
<div class="signup-header">Sustainable Living</div>
<span class="closebtn" onclick="setSignup('hide');this.parentElement.style.display='none';">×</span>
<div class="signup-container">
<p>Get new articles related to <em>sustainability</em> and <em>eco-friendly home decor</em> direct to your inbox. We respect your privacy.</p>
<form action="https://reclaimdesign.us9.list-manage.com/subscribe/post?u=0c1d87de694b90628655f4ab9&id=bab84d57de" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" rel="noopener" novalidate>
<div id="mc_embed_signup_scroll">
<div class="mc-field-group">
<input type="email" value="" name="EMAIL" class="required email" id="mce-EMAIL" placeholder="Please Enter Your Email Address" required autocomplete="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>
<div style="position: absolute; left: -5000px;" aria-hidden="true"><input type="text" name="b_0c1d87de694b90628655f4ab9_bab84d57de" tabindex="-1" value=""></div>
<div class="clear"><input type="submit" value="Subscribe" name="subscribe" id="mc-embedded-subscribe" class="button"></div>
</div>
</form>
</div>
</div>
Yes your getSignup is not called correctly.
Here you can see the alternative solution without jquery.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<script>
function setSignup(val) {
localStorage.setItem("popState", val);
}
function getSignup() {
if (localStorage.getItem("popState") == 'hide') {
//$(".signup").hide();
document.querySelector('.signup').style.display = 'none';
} else if (localStorage.getItem("popState") != 'hide') {
document.querySelector('.signup').style.display = 'block';
}
}
window.addEventListener("load", getSignup);
</script>
<div class="signup">
<div class="signup-header">Sustainable Living</div>
<span class="closebtn" onclick="setSignup('hide');this.parentElement.style.display='none';">×</span>
<div class="signup-container">
<p>Get new articles related to <em>sustainability</em> and <em>eco-friendly home decor</em> direct to your inbox. We respect your privacy.</p>
<form action="https://reclaimdesign.us9.list-manage.com/subscribe/post?u=0c1d87de694b90628655f4ab9&id=bab84d57de" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" rel="noopener" novalidate>
<div id="mc_embed_signup_scroll">
<div class="mc-field-group">
<input type="email" value="" name="EMAIL" class="required email" id="mce-EMAIL" placeholder="Please Enter Your Email Address" required autocomplete="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>
<div style="position: absolute; left: -5000px;" aria-hidden="true"><input type="text" name="b_0c1d87de694b90628655f4ab9_bab84d57de" tabindex="-1" value=""></div>
<div class="clear"><input type="submit" value="Subscribe" name="subscribe" id="mc-embedded-subscribe" class="button"></div>
</div>
</form>
</div>
</div>
</body>
</html>
Thanks very much for your input guys. I got it working with the following (for anyone who might come up against the same issue)...
HTML:
<div class="signup">
<div class="signup-header">Sustainable Living</div>
<div class="signup-container">
<p>Get new articles related to <em>sustainability</em> and <em>eco-friendly home decor</em> direct to your inbox. We respect your privacy.</p>
<form action="https://reclaimdesign.us9.list-manage.com/subscribe/post?u=0c1d87de694b90628655f4ab9&id=bab84d57de" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" rel="noopener" novalidate>
<div id="mc_embed_signup_scroll">
<div class="mc-field-group">
<input type="email" value="" name="EMAIL" class="required email" id="mce-EMAIL" placeholder="Please Enter Your Email Address" required autocomplete="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;" aria-hidden="true"><input type="text" name="b_0c1d87de694b90628655f4ab9_bab84d57de" tabindex="-1" value=""></div>
<div class="clear"><input type="submit" value="Subscribe" name="subscribe" id="mc-embedded-subscribe" class="button"></div>
</div>
</form>
</div>
</div>
CSS:
.signup {
bottom: 2%;
display: none;
margin-right: -15px !important;
max-width: 280px;
position: fixed;
right: 2%;
z-index: 9999;
}
.signup-header {
background: #539c22;
border-radius: 10px 10px 0 0;
color: #ffffff;
font-family: 'Carrois Gothic', sans-serif;
font-size: 20px;
padding: 25px 15px;
text-transform: uppercase;
}
.signup-container {
background-color: #6db240;
border-radius: 0 0 10px 10px;
color: #ffffff;
padding: 15px;
}
.closebtn {
color: #ffffff;
cursor: pointer;
font-size: 30px;
position: absolute;
right: 15px;
top: 5px;
}
.closebtn:hover {
color: #6db240;
}
.signup-container .button {
background-color: #539c22;
border: 0 none;
border-radius: 5px;
color: #ffffff !important;
cursor: pointer;
font-size: 15px;
height: 32px;
line-height: 32px;
margin: 0 15px 0 0 !important;
text-align: center;
transition: all 0.23s ease-in-out 0s;
width: 100% !important;
}
.signup-container .button:hover {
opacity: 0.7;
}
.signup-container .mc-field-group input {
display: block;
padding: 8px 0;
text-indent: 2%;
width: 100%;
}
.signup-container input {
border: 1px solid #d0d0d0;
border-radius: 5px;
cursor: auto;
font-family: 'Open sans', sans-serif;
font-size: 15px;
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
}
JQuery:
$(document).ready(function() {
$('.signup').css('display', 'block');
$PopUp = $('.signup');
var hide = JSON.parse(localStorage.getItem('hide'));
if (hide) {
$PopUp.hide();
} else {
// initialize value in case it hasn't been set already
localStorage.setItem('hide', false);
}
$('.closebtn').click(function() {
$('.signup' ).hide();
// toggle the boolean by negating its value
var hide = JSON.parse(localStorage.getItem('hide'));
localStorage.setItem('hide', !hide);
});
});
I want my 'sales bar' to slid-up after the user click the close 'x' button.
it was all working fine -with the close button - but then I added a form, and if I put the close button inside the form (to get it in-line) then the slideUp only last a second, and the bar slides back down - it should stay 'gone'.
<html>
<head>
<title></title>
<style type="text/css">
body {
margin: 0px;
}
.top-general-alert {
padding: 8px;
border: none;
font-size: 1em;
line-height: 2em;
text-align: center;
display: none;
background-color: #00294e;
color: #ffee7a;
}
.top-general-alert {
color: #fff;
}
.top-general-alert a,
.top-general-alert a:hover {
color: #0099cc;
}
</style>
</head>
<body>
<div class="top-general-alert" >
<form class="form-inline">
<div class="form-group">
<label for="newsletter">Sign-up for our newsletter! </label>
<input type="email" class="form-control" id="newsletter" placeholder="Your Email...">
<button type="submit" class="btn btn-default">Sign-up!</button> <button class="close-top-general-alert" >×</button>
</div>
</form>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
if ( $('.top-general-alert').length > 0 ) {
$('.top-general-alert').delay(800).slideDown('medium');
$('.close-top-general-alert').click( function() {
$('.top-general-alert').slideUp('fast');
});
}
});
</script>
</body>
</html>
(credit to https://www.buildersociety.com/threads/hellobar-free-alternative-devseries.1519/)
To be clear; If I make this modification (below) moving the close button outside the form. The behavior is correct. But the button is below the form
<div class="top-general-alert" >
<form class="form-inline">
<div class="form-group">
<label for="newsletter">Sign-up for our newsletter! </label>
<input type="email" class="form-control" id="newsletter" placeholder="Your Email...">
<button type="submit" class="btn btn-default">Sign-up!</button>
</div>
</form>
×
How about hide() after slideUp()?
$('.top-general-alert').slideUp('fast').hide('fast');
EDIT: form buttons cause page reload. Add type=button or type=reset will do work.
Full example below:
$(document).ready(function() {
if ( $('.top-general-alert').length > 0 ) {
$('.top-general-alert').delay(800).slideDown('medium');
$('.close-top-general-alert').click( function() {
$('.top-general-alert').slideUp('fast').hide('fast');
});
}
});
body {
margin: 0px;
}
.top-general-alert {
padding: 8px;
border: none;
font-size: 1em;
line-height: 2em;
text-align: center;
display: none;
background-color: #00294e;
color: #ffee7a;
}
.top-general-alert {
color: #fff;
}
.top-general-alert a,
.top-general-alert a:hover {
color: #0099cc;
}
<div class="top-general-alert" >
<form class="form-inline">
<div class="form-group">
<label for="newsletter">Sign-up for our newsletter! </label>
<input type="email" class="form-control" id="newsletter" placeholder="Your Email...">
<button type="submit" class="btn btn-default">Sign-up!</button> <button type="reset" class="close-top-general-alert" >×</button>
</div>
</form>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
How to validate a multiple step form and message display for each and every fields example:please enter your email and I also want all the error message to
be display at the same time :suppose I click on next button I should display all How to validate a multiple step form and message display for each and every feilds How to validate a multiple step form and message display for each and every fields
function isEmail(str) { // simple email validation
return /(.+)#(.+){2,}\.(.+){2,}/.test($.trim(str));
}
function isEmpty(str) { // test for empty string
return $.trim(str) === "";
}
function validate($div) { // validates any div - will not let you leave the div if error
var $fields = $div.find("input"), hasError = false;
$fields.each(function() {
$(this).removeClass("error")
hasError = this.name=="pword" && isEmpty(this.value);
if (hasError) {
$("#pword").addClass("error").focus();
return false;
}
hasError = this.name=="email" && (isEmpty(this.value) || !isEmail(this.value));
if (hasError) {
$("#email").addClass("error").focus();
return false;
}
hasError = isEmpty(this.value); // the rest of the fields
if (hasError) {
$(this).addClass("error").focus();
return false;
}
})
return hasError?false:true;
}
$(function() {
// validate all divs on submit, but actually only necessary to validate thediv the submit is on
$("#myForm").on("submit",function(e) {
$(".page").each(function() {
if (!validate($(this))) {
e.preventDefault(); // stop submission
return false;
}
});
});
$(".nav").on("click", function() {
var $parent = $(this).closest("div");
var $nextDiv = $(this).hasClass("next") ? $parent.next() : $parent.prev();
if (validate($parent)) { // is the div this button is on valid?
$parent.fadeOut(function() { // fade it out and fade the next one in
if ($nextDiv.length) {
$nextDiv.fadeIn()
for (var i=$(".page").length;i> $nextDiv.index(); i--) {
$("#bar" + i).css({"background-color": "#D8D8D8"}); // we are going backwards
}
$("#bar" + $nextDiv.index()).css({"background-color": "#38610B"});
}
});
}
});
});
body {
margin: 0 auto;
padding: 0;
text-align: center;
background-color: #D8D8D8;
}
#wrapper {
width: 995px;
padding: 0px;
margin: 0px auto;
font-family: helvetica;
position: relative;
}
#wrapper .baricon {
display: inline-block;
border-radius: 100%;
padding: 12px;
background-color: #38610B;
color: white;
}
#wrapper .progress_bar {
width: 200px;
height: 5px;
border-radius: 20px;
background-color: #D8D8D8;
display: inline-block;
}
#wrapper form div {
margin-left: 340px;
padding: 10px;
box-sizing: border-box;
width: 300px;
margin-top: 50px;
background-color: #585858;
}
#wrapper form div p {
color: #F2F2F2;
margin: 0px;
margin-top: 10px;
font-weight: bold;
}
#wrapper form div .form_head {
font-size: 22px;
font-weight: bold;
margin-bottom: 30px;
}
#wrapper form div input[type="text"] {
width: 200px;
height: 40px;
padding: 5px;
border-radius: 5px;
border: none;
margin-top: 10px;
}
#wrapper form div input[type="button"],
input[type="submit"] {
width: 80px;
height: 40px;
border-radius: 5px;
border: 2px solid white;
background: none;
color: white;
margin: 5px;
margin-top: 10px;
}
#user_details,
#qualification {
display: none;
}
.error { background-color:pink !important}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div id="wrapper">
<br>
<span class='baricon'>1</span>
<span id="bar1" class='progress_bar'> </span>
<span class='baricon'>2</span>
<span id="bar2" class='progress_bar'> </span>
<span class='baricon'>3</span>
<form method="post" action="" id="myForm">
<div id="account_details" class="page">
<p class='form_head'>Account Details</p>
<p>Email Address</p>
<input type="text" name="email" id="email" placeholder='Email Address'>
<p>Password</p>
<input type="text" name="pword" id="pword" placeholder='Password'>
<br>
<input type="button" value="Next" class="nav next" />
</div>
<div id="user_details" class="page">
<p class='form_head'>User Details</p>
<p>First Name</p>
<input type="text" name="fname" id="fname" placeholder='First Name'>
<p>Last Name</p>
<input type="text" name="lname" is="lname" placeholder='Last Name'>
<p>Gender</p>
<input type="text" name="gender" id="gender" placeholder='Gender'>
<br>
<input type="button" value="Prev" class="nav prev" />
<input type="button" value="Next" class="nav next" />
</div>
<div id="qualification" class="page">
<p class='form_head'>Qualification</p>
<p>Qualification</p>
<input type="text" placeholder='Qualification'>
<p>Hobbies</p>
<input type="text" placeholder='Hobbies'>
<br>
<input type="button" value="Prev" class="nav prev" />
<input type="Submit" value="Submit">
</div>
</form>
</div>
You can use Jquery.validate.min.js file which contains validate method.
Refer the following code below:
function valid(){
$("#rform").validate({
rules:{
uname:"required", // uname, email are input names
umail:{
required:true,
email:true
},
upass:{
required:true,
minlength:8
}
},
messages:{
uname:"Please enter full name",
umail:{
required:"Please enter email id",
email:"Please enter valid email id"
},
upass:
{
required:"please provide password",
minlength:"min length of password is 8"
}
},
submitHandler :function(form){
// alert("it works!");
console.log("it works!");
// form.submit();
funreg(); //function to be called after submit button is pressed and al inputl fields are valids
}
});
}