I'm trying to set up user accounts with my Meteor app. Right now I have the login and register forms made, but they don't work. Does anyone know how to do this? Here is the code I have: http://jsfiddle.net/5AMWE5T/X8aJf/1/
html:
<body>
<div id="topbar">
<form id="login-form" action="/">
<div>
<input type="email" id="login-email" />
<input type="password" id="login-password" />
<input type="submit" class="btn btn-info" id="login-button" value="Sign in" />
</div>
</form>
</div>
<div id="register-box">
<form id="register-form" action="action">
<div>
<input type="username" id="account-username" placeholder=" Username" />
<input type="email" id="account-email" placeholder="Email" />
<input type="password" id="account-password" placeholder="Password" />
<input type="submit" class="btn btn-success" id="create-account" value="Sign up" />
</div>
</form>
</div>
css:
#topbar {
height: 40px;
width: 100%;
opacity: 1;
background-color: #47a7d3;
box-shadow: 0.1em 0.1em 0.1em;
position: absolute;
top: 0;
left: 0;
padding: 0;
}
#register-form {
text-align: center;
margin-top: 15px;
}
#account-username {
margin-bottom: 0.75em;
border-radius: 0.3em;
border-width: 0.1em;
border-color: #ffffff;
width: 15.4em;
margin-left: 0.1em;
height: 1.8em;
box-shadow: 0 0 0.1em #676767;
}
#login-form {
position: absolute;
width: 100%;
top: 0.3em;
letter-spacing: 0.1em;
right: 0.33em;
text-align: right;
}
#login-email {
width: 180px;
}
#login-password {
width: 100px;
}
#login-button {
position: relative;
top: -5px;
font-family:'Montserrat Alternates';
font-size: 12px;
color: #ffffff;
letter-spacing: 0.05em;
}
javascript:
Template.login.events({
'submit #login-form': function (e, t) {
e.preventDefault();
// retrieve the input field values
var email = t.find('#login-email').value,
password = t.find('#login-password').value;
// Trim and validate your fields here....
var trimInput = function (val) {
return val.replace(/^\s*|\s*$/g, "");
}
var email = trimInput(email);
// If validation passes, supply the appropriate fields to the
// Meteor.loginWithPassword() function.
Meteor.loginWithPassword(email, password, function (err) {
if (err)
// The user might not have been found, or their password
// could be incorrect. Inform the user that their
// login attempt has failed.
console.log("Your email or password are incorrect")
else
// The user has been logged in.
console.log("You have been logged in!")
});
return false;
}
});
Your code wouldn't work with a fiddle btw.
A couple of things:
Make sure you have accounts-password installed you can do this with meteor add accounts-password
You haven't given the code for registrations but assuming you use an email for registration, you should log in this way with the {email: email}.
Meteor.loginWithPassword({email: email, password, function (err) {
It would also be a bit more helpful if you gave a bit more info on how you feel it doesn't work. Does submitting the page refresh the page? Do you have any javascript errors in your console? Do you get an error message back?
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>
Hello Developers/Programmers, I am having a problem resolving this issue since it's my first time creating my website. I want to send email from my website to my gmail and I used "submit" it's not working and it's always reloading upon clicking it.
Please bear with my codes I just copied some of my codes from different video tutorials and I don't understand some.
//index.html
<script src="https://smtpjs.com/v3/smtp.js"></script>
<script src="app.js"></script>
<div class= "contactMe">
<form action="" method="post">
<h2>Send Message</h2>
<div class = "inputBox">
<input type= "text" class="name" name="" required= "required" placeholder="Full Name">
</div>
<div class = "inputBox">
<input type= "text" class="email" name="" required= "required" placeholder="Your Email">
</div>
<div class = "inputBox">
<textarea placeholder="Your message here..." class="message" required= "required"></textarea>
</div>
<div class = "inputBox">
<input type = "submit" class="submitButton" name="" value="Send" onclick="sendEmail()">
</div>
</form>
</div>
//style.css
.contactMe{
position:absolute;
bottom:20%;
left:10%;
width: 50%;
display:none;
}
.contactMe h2{
font-size: 30px;
color: white;
font-weight: 500;
margin:20px;
}
}
.contactMe .inputBox{
position: relative;
width: 10%;
/*margin-top: 10px;*/
border: 3px solid black;
}
.contactMe .inputBox input , textarea{
width: 50%;
padding: 5px 0;
font-size: 16px;
margin: 10px 0;
background-color: rgba(0,0,0,0.7);
color: white;
border: none;
border-bottom: 2px solid #333;
outline: none;
resize: none;
}
.contactMe .inputBox textarea{
height: 135px;
}
.contactMe .inputBox input[type="submit"]{
width: 100px;
background: white;
color: black;
cursor: pointer;
padding: 10px;
font-size: 18px;
}
//app.js
document.querySelector(".submitButton").addEventListener("submit",
function(e){
e.preventDefault();
}
function sendEmail() {
Email.send({
Host : "smtp.gmail.com",
Username : "myemail#gmail.com",
Password : "Mypassword",
To : 'myemail#gmail.com',
From : "myemail#gmail.com",
Subject : $name + "sent you a message",
Body : "Name:" + $name <br/> "Email:" <br/> "Message:",
}
).then(message => alert("Message successfully sent"));
}
Thank you for understanding my codes. If you know what goes wrong in my code why it's not working please tell me.
The main problem is the statement, which is preventing the form to be submitted ( you call this refreshing, but it is not. when your browser opens your page for the 1st time - it makes GET and after hitting the submit button - it makes POST )
document.querySelector(".submitButton").addEventListener("submit" is the event of the form - not of the submit button
you have not closed the statement properly, it should look like
document.querySelector(".emailForm").addEventListener("submit", function(e){ e.preventDefault(); });
Another problem is the construction of subject and body of your email, you should use this Template literals with ` character instead of "
Also, you should initialize the variable name with the value from the <input type= "text" class="name" by using var name = document.querySelector(".name").value;
So the corrected snippet looks like
<form action="" method="post" class="emailForm">
...
document.querySelector(".emailForm").addEventListener("submit", function(e){
e.preventDefault();
});
function sendEmail() {
var name = document.querySelector(".name").value;
Email.send({
Host : "smtp.gmail.com",
Username : "myemail#gmail.com",
Password : "Mypassword",
To : 'myemail#gmail.com',
From : "myemail#gmail.com",
Subject : `${name} sent you a message`,
Body : `Name: ${name} <br/> Email: <br/> Message:`,}).then(message => alert("Message successfully sent"));
}
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
}
});
}
document.getElementById("button1").addEventListener("click", mouseOver1);
function mouseOver1(){
document.getElementById("button1").style.color = "red";
}
document.getElementById("button2").addEventListener("click", mouseOver);
function mouseOver(){
document.getElementById("button2").style.color = "purple";
}
$("#button1").hover(function() {
$(this).css('cursor','pointer');
});
$("#button2").hover(function() {
$(this).css('cursor','pointer');
});
if($(".existing1-username-input-textbox").get(0).val()== "Micheal22" && $(".existing2-password-input-textbox").get(0).val()== "honor7thG")
{
$('#button1').on('click', function () {
$('.username-label').animate({'left': '-105%'});
// but I want all the old content to slide to the left if username and password match above
// then new content should slide in from the right.
});
}else{
$(".existing1-username-input-textbox").firstChild.nodeValue="The existing username is not correct";
$(".password-new-input-textbox").firstChild.nodeValue="The existing password is not correct";
}
.intro h1 {
font-family: 'Cambria';
font-size: 16pt;
font: bold;
text-align: left;
}
.intro p {
font-family: 'Calibri';
font: italic;
font-size: 12pt;
padding: 0px 690px 0px 20px;
text-align: left;
}
.content {
border: 2px solid;
-webkit-border-radius: 10px;
-moz-border-radius: 10px;
border-radius: 10px;
}
#para1 {
padding: 0px 1050px 0px 20px;
}
#para2 {
padding: 0px 1099px 0px 20px;
}
.username-label,
.password-label {
margin: 10px 0px 0px 300px;
position: relative;
top: -70px;
}
.existing1-username-input-textbox,
.existing2-password-input-textbox
{
top: -70px;
position: relative;
}
#button1{
background-color: #add8e6;
margin-left: 390px;
position: relative;
top: -50px;
-webkit-border-radius: 10px;
-moz-border-radius: 10px;
border-radius:10px;
padding: 0px 20px 0px 20px;
}
#button2{
background-color: #add8e6;
margin-left: -200px;
position: relative;
top: -30px;
-webkit-border-radius: 10px;
-moz-border-radius: 10px;
border-radius: 10px;
padding: 0px 20px 0px 20px;
}
.Username-label1,
.Password-label2,
.Email-label3,
.Repeat-Email-label4
{
margin: 0px 0px 0px 300px;
position: relative;
top: -70px;
}
.username-new-input-textbox,
.password-new-input-textbox,
.email-new-input-textbox,
.reenter-new-input-textbox{
position: relative;
top: -70px;
margin-left: 20px;
}
<html>
<head>
<link href="Home.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<title>Project</title>
</head>
<body>
<div class="container">
<div class="intro">
<h1>Welcome to Cuyahoga Community College Student Services Online</h1>
<p>Cuyahoga Community College recognizes students' rights to access personal and academic records in accordance with the Family Educational Rights and Privacy Act of 1974 (FERPA) as amended by Public Law 93-568.</p>
</div>
<br/>
<div class="content">
<div class="row top">
<p id="para1">Already have an account with us? Returning users may log in by entering their site username and password. </p>
<div class="login">
<label class="username-label" for="username-part1">Username</label>
<input class="existing1-username-input-textbox" type="text" value="" />
<br/><br/>
<label class="password-label" for="password-part2">Password</label>
<input class="existing2-password-input-textbox" type="password" value="" />
<br/>
<button id="button1">Log in</button>
</div>
</div>
<hr/>
<div class="row bottom">
<p id="para2">New users, please create a new account by providing us with some basic information.</p>
<div class= "new_customers_info">
<label class="Username-label1" for="new-user-name-part-1">Username</label>
<input class="username-new-input-textbox" type="text" value="" />
<br/><br/>
<label class="Password-label2" for="password-new-part2">Password</label>
<input class="password-new-input-textbox" type="password" value="" />
<br/><br/>
<label class="Email-label3" for="email-new">Email Address</label>
<input class="email-new-input-textbox" type="text" value=""/>
<br/><br/>
<label class="Repeat-Email-label4" for="repeat-new-email">Repeat Email Address</label>
<input class="reenter-new-input-textbox" type="text" value="" />
<button id="button2">Create Account</button>
</div>
</div>
</div>
<br/>
<footer>Cuyahoga Community College</footer>
<footer>700 Carnegie Avenue, Cleveland, Ohio, 44115</footer>
</div>
<script src="Home.js"></script>
</body>
</html>
How can I get my current content to slide to the left and bring in new content from the right (after clicking on button 1) when an existing student's username and password are correct, and if it's not correct display error messages that either the username or password isn't correct below each respective textbox .I am thinking about using an if/else condition. Also, how would I load the student's existing account information upon sliding it from the right, if I haven't created the content yet? If I already created the content to be slide in from the right, where do I hold that information until it's time to display that new content. Here is my code so far.
Below piece of code will execute when page get loaded and at that time username and password fields will be blank, so no event will get associated with login button :
if($(".existing1-username-input-textbox").get(0).val()== "Micheal22" && $(".existing2-password-input-textbox").get(0).val()== "honor7thG")
{
$('#button1').on('click', function () {
$('.username-label').animate({'left': '-105%'});
// but I want all the old content to slide to the left if username and password match above
// then new content should slide in from the right.
});
}else{
$(".existing1-username-input-textbox").firstChild.nodeValue="The existing username is not correct";
$(".password-new-input-textbox").firstChild.nodeValue="The existing password is not correct";
}
You should change this to below :
$('#button1').on('click', function () {
if($(".existing1-username-input-textbox").get(0).value== "Micheal22" && $(".existing2-password-input-textbox").get(0).value== "honor7thG")
{
$('.username-label').animate({'left': '-105%'});
// but I want all the old content to slide to the left if username and password match above
// then new content should slide in from the right.
}else{
$(".existing1-username-input-textbox").firstChild.nodeValue="The existing username is not correct";
$(".password-new-input-textbox").firstChild.nodeValue="The existing password is not correct";
}
});
Now this will associate click event with login button on page load, so when you click login, it will first check the username and password, if matched then the animation part will take effect otherwise else part will execute.
one quick way to do it is via JQuery's .animate function.
Here is a little fiddle with the example:
http://jsfiddle.net/f7VdQ/135/
$(function () {
$('a').on('click', function () {
$('.left').animate({'left': '-105%'});
$('.right').animate({'left': '0px'});
});
$('p').on('click', function () {
$('.left').animate({'left': '10'});
$('.right').animate({'left': '105%'});
});
})
PS.: If you dont want to the current content to be overlayed (that's an additional funcionallity of the fiddle) just dont use z-indexes on the CSS and also use relative positioning.
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.