I am making a function in JS that prevents you from submitting if there is something wrong.
When I click the submit button it does not check if the code is valid, which really bugs me. My expected outcome is to redirect to another page if it is valid, which doesn't happen! Please help!
const formm = document.querySelector('#CreateAccount')
const school = document.querySelector('#skool');
const username = document.querySelector('#username');
const email = document.querySelector('#email');
const pwd = document.querySelector('#password');
const conf = document.querySelector('#confpassword');
formm.addEventListener("submit", (event) => {
if (isFormValid() == true) {
window.location.assign("start.html");
console.log(2);
} else {
event.preventDefault();
console.log(30);
}
validateForm();
console.log(30);
});
function isFormValid() {
const inputscontainers = document.querySelectorAll('.inputs')
let result = true;
inputscontainers.forEach((container) => {
if (container.classList.contains("error")) {
return false;
}
})
}
function validateForm() {
if (username.value.trim() == '') {
setError(username, 'Name cannot be empty');
} else if (username.value.trim() < 5) {
setError(username, 'Idrc');
console.log(3);
} else {
setSuccess(username);
}
if (email.value.trim() == '') {
setError(email, 'You forgot to fill in your email.');
} else if (isEmailValid(email.value)) {
setSuccess(email);
} else {
setError(email, "Provide a valid email");
}
if (pwd.value.trim() == '') {
setError(pwd, "Password can't be empty");
} else if (pwd.value.trim().length < 6 || pwd.value.trim().length > 20) {
setError(pwd, 'Length must be minimum 6 characters and max 20.');
} else {
setSuccess(pwd);
}
if (conf.value.trim() == '') {
setError(conf, 'This is an empty password');
} else if (conf.value !== pwd.value) {
setError(conf, 'Passwords dont match');
} else {
setSuccess(conf);
}
}
function setError(elementr, errorMessage) {
const parents = elementr.parentElement;
parents.classList.add("error");
parents.classList.remove("success");
const paragraph = parents.querySelector('p').textContent = errorMessage;
}
function setSuccess(elementr) {
const parents = elementr.parentElement;
parents.classList.add("success");
parents.classList.remove("error");
}
function isEmailValid(email) {
const reg = /^(([^<>()[\]\.,;:\s#\"]+(\.[^<>()[\]\.,;:\s#\"]+)*)|(\".+\"))#(([^<>()[\]\.,;:\s#\"]+\.)+[^<>()[\]\.,;:\s#\"]{2,})$/i;
return reg.test(email);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<form id="CreateAccount" action="start.html" method="GET">
<div class="main">
<div class="Title">
<h1>Enter your details.</h1>
</div>
<div class="inputs">
<label for="skool">SchoolName:</label>
<input type="text" id="skool" placeholder="Put the school name" name="skool"></input>
<i class="fa-solid fa-circle-xmark"></i>
<i class="fa-solid fa-circle-check"></i>
<p>Error Message</p>
</div>
<div class="inputs">
<label for="username">Username:</label>
<input type="text" id="username" placeholder="Username" name="username">
<i class="fa-solid fa-circle-xmark"></i>
<i class="fa-solid fa-circle-check"></i>
<p id="p">Error Message</p>
</div>
<div class="inputs">
<label for="password">Password</label>
<input type="password" id="password" placeholder=" Password" name="password"></input>
<i class="fa-solid fa-circle-xmark"></i>
<i class="fa-solid fa-circle-check"></i>
<p id="p">Error Message</p>
</div>
<div class="inputs">
<label for="confpassword">Confirm Password</label>
<input type="password" id="confpassword" placeholder=" Confirm Password" name="confpassword"></input>
<i class="fa-solid fa-circle-xmark"></i>
<i class="fa-solid fa-circle-check"></i>
<p>Error Message</p>
</div>
<div class="inputs">
<label for="email">Email:</label>
<input type="email" id="email" placeholder="Email" name="email"></input>
<i class="fa-solid fa-circle-xmark"></i>
<i class="fa-solid fa-circle-check"></i>
<p>Error Message</p>
</div>
<button class="submitbtn" type="submit">Submit</button>
</div>
</div>
Other than the inversion on validation / isValidForm, your isValidForm function doesn't return a result, so it can't be compared on a if statement
Here's how to fix it
formm.addEventListener("submit", (event) => {
validateForm();
if (isFormValid() == true) {
window.location.assign("start.html");
} else {
event.preventDefault();
}
});
function isFormValid() {
const inputscontainers = document.querySelectorAll('.inputs')
let result = true;
inputscontainers.forEach((container) => {
if (container.classList.contains("error")) {
return false;
}
})
return result;
}
Related
i have a simple form where i am doing some validations in javascript, the submit button is prevented by default to check if all validations are done the form is like below:
const form = document.getElementById('form');
const username = document.getElementById('username');
const email = document.getElementById('email');
const password = document.getElementById('password');
form.addEventListener('submit', e => {
e.preventDefault();
checkInputs();
});
function checkInputs() {
// trim to remove the whitespaces
const usernameValue = username.value.trim();
const emailValue = email.value.trim();
const passwordValue = password.value.trim();
if (usernameValue === '') {
setErrorFor(username, 'Full name cannot be blank');
} else {
setSuccessFor(username);
}
if (emailValue === '') {
setErrorFor(email, 'Email cannot be blank');
} else if (!isEmail(emailValue)) {
setErrorFor(email, 'Not a valid email');
} else {
setSuccessFor(email);
}
if (passwordValue === '') {
setErrorFor(password, 'Roll number cannot be blank');
} else if (passwordValue.length < 10) {
setErrorFor(password, 'Roll number must be 10 digits');
} else {
setSuccessFor(password);
}
}
function setErrorFor(input, message) {
const formControl = input.parentElement;
const small = formControl.querySelector('small');
formControl.className = 'form-control error';
small.innerText = message;
}
function setSuccessFor(input) {
const formControl = input.parentElement;
formControl.className = 'form-control success';
}
function isEmail(email) {
return /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(email);
}
<form id="form" class="form" method="post" action="">
<div class="form-control">
<label for="username">Full Name</label>
<input type="text" placeholder="Full Name" id="username" />
<i class="fas fa-check-circle"></i>
<i class="fas fa-exclamation-circle"></i>
<small>Error message</small>
</div>
<div class="form-control">
<label for="username">Email</label>
<input type="email" placeholder="Email" id="email" />
<i class="fas fa-check-circle"></i>
<i class="fas fa-exclamation-circle"></i>
<small>Error message</small>
</div>
<div class="form-control">
<label for="username">Roll Number</label>
<input type="text" maxlength="10" placeholder="Roll Number" id="password" />
<i class="fas fa-check-circle"></i>
<i class="fas fa-exclamation-circle"></i>
<small>Error message</small>
</div>
<button type="submit">Submit</button>
</form>
the validations are working fine, the issue if the form is not getting submitted if all validations are successful, can anyone please tell me how to accomplish this, thanks in advance
Not getting submitted becouse for e.preventDefault();. So e.preventDefault(); exicute when form is not valid otherwise not needed.
const form = document.getElementById('form');
const username = document.getElementById('username');
const email = document.getElementById('email');
const password = document.getElementById('password');
form.addEventListener('submit', e => {
if(!checkInputs())
e.preventDefault();
});
function checkInputs() {
// trim to remove the whitespaces
const usernameValue = username.value.trim();
const emailValue = email.value.trim();
const passwordValue = password.value.trim();
let error =true;
if (usernameValue === '') {
setErrorFor(username, 'Full name cannot be blank');
error =false;
} else {
setSuccessFor(username);
}
if (emailValue === '') {
setErrorFor(email, 'Email cannot be blank');
error =false;
} else if (!isEmail(emailValue)) {
setErrorFor(email, 'Not a valid email');
error =false;
} else {
setSuccessFor(email);
}
if (passwordValue === '') {
setErrorFor(password, 'Roll number cannot be blank');
error =false;
} else if (passwordValue.length < 10) {
setErrorFor(password, 'Roll number must be 10 digits');
error =false;
} else {
setSuccessFor(password);
}
return error;
}
function setErrorFor(input, message) {
const formControl = input.parentElement;
const small = formControl.querySelector('small');
formControl.className = 'form-control error';
small.innerText = message;
}
function setSuccessFor(input) {
const formControl = input.parentElement;
formControl.className = 'form-control success';
}
function isEmail(email) {
return /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(email);
}
<form id="form" class="form" method="post" action="">
<div class="form-control">
<label for="username">Full Name</label>
<input type="text" placeholder="Full Name" id="username" />
<i class="fas fa-check-circle"></i>
<i class="fas fa-exclamation-circle"></i>
<small>Error message</small>
</div>
<div class="form-control">
<label for="username">Email</label>
<input type="email" placeholder="Email" id="email" />
<i class="fas fa-check-circle"></i>
<i class="fas fa-exclamation-circle"></i>
<small>Error message</small>
</div>
<div class="form-control">
<label for="username">Roll Number</label>
<input type="text" maxlength="10" placeholder="Roll Number" id="password" />
<i class="fas fa-check-circle"></i>
<i class="fas fa-exclamation-circle"></i>
<small>Error message</small>
</div>
<button type="submit">Submit</button>
</form>
I have this error message below despite setting the javascript in the html. The code below is my html code for registration but none of the javascript function or event listener are working. I am still learning about javascript and html so please advice on what I did wrong.
Error message
Uncaught ReferenceError: matchTest is not defined at HTMLInputElement.onkeyup
Register page
<div class="form">
<form id="register-form" action="#">
<ul class="form-container">
<li>
<h2>Create Account</h2>
</li>
<li>
<label for="name">Name</label>
<input type="name"
name="name"
id="name"
required />
</li>
<li>
<label for="email" class="emailBox">Email</label>
<input type="email"
name="email"
id="email"
required
/>
<span class="emailText"></span>
</li>
<li>
<label for="password" class="passBox">Password</label>
<input type="password"
id="password"
name="password"
class="password"
required
/>
<span class="passText"></span>
</li>
<li>
<label for="re-password">Re-Enter Password</label>
<input type="password"
id="re-password"
name="re-password"
class="re-password"
onkeyup="matchTest()"
required
/>
</li>
<li>
<button type="submit" class="primary">
Register
</button>
</li>
<li>
<div>Already have an account? Sign-In
</div>
</li>
</ul>
</form>
<script type="text/javascript">
window.onload = function() {
let email = document.getElementById("email")
let password = document.getElementById("password")
email.addEventListener('input',()=>{
let emailBox = document.querySelector('.emailBox')
let emailText = document.querySelector('.emailText')
const emailPattern = /[A-Za-z0-9._%+-]+#[A-Za-z0-9.-]+\.[A-Za-z]{1,63}$/
if(email.value.match(emailPattern)){
emailBox.classList.add('valid')
emailBox.classList.remove('invalid')
emailText.innerHTML = "Your Email Address in Valid"
}else{
emailBox.classList.add('invalid')
emailBox.classList.remove('valid')
emailText.innerHTML = "Must be a valid email address."
}
})
password.addEventListener('input',()=>{
let passBox = document.querySelector('.passBox');
let passText = document.querySelector('.passText');
const passPattern = /(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}/;
if(password.value.match(passPattern)){
passBox.classList.add('valid');
passBox.classList.remove('invalid');
passText.innerHTML = "Your Password in Valid";
}else{
passBox.classList.add('invalid');
passBox.classList.remove('valid');
passText.innerHTML = "Your password must be at least 8 characters as well as contain at least one uppercase, one lowercase, and one number.";
}
})
function matchTest(){
let password = document.querySelector('password').value
let confirmPassword = document.querySelector('re-password').value
if(password != confirmPassword)
alert("Password don't match. Please try again.")
return false
}
else if(password == confirmPassword){
alert("Password match")
}
}
}
</script>
</div>
You need to change following things:
It is recommended to define addEventListener in JS not inline
repeatPassword.addEventListener("keyup", (e) => { matchTest(); });
Since you've defined the variable password, so it would be consistent to add repeatPassword also and get its value as password.value and reapatPassword.value in matchTest.
It is recommended to use === instead of ==.
I've used console.log in place of alert. Since you are checking for password equality then it's annoying to get alert after every key press.
window.onload = function() {
let email = document.getElementById("email");
let password = document.getElementById("password");
let repeatPassword = document.getElementById("re-password");
email.addEventListener("input", () => {
let emailBox = document.querySelector(".emailBox");
let emailText = document.querySelector(".emailText");
const emailPattern = /[A-Za-z0-9._%+-]+#[A-Za-z0-9.-]+\.[A-Za-z]{1,63}$/;
if (email.value.match(emailPattern)) {
emailBox.classList.add("valid");
emailBox.classList.remove("invalid");
emailText.innerHTML = "Your Email Address in Valid";
} else {
emailBox.classList.add("invalid");
emailBox.classList.remove("valid");
emailText.innerHTML = "Must be a valid email address.";
}
});
password.addEventListener("input", () => {
let passBox = document.querySelector(".passBox");
let passText = document.querySelector(".passText");
const passPattern = /(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}/;
if (password.value.match(passPattern)) {
passBox.classList.add("valid");
passBox.classList.remove("invalid");
passText.innerHTML = "Your Password in Valid";
} else {
passBox.classList.add("invalid");
passBox.classList.remove("valid");
passText.innerHTML =
"Your password must be at least 8 characters as well as contain at least one uppercase, one lowercase, and one number.";
}
});
function matchTest() {
let pass = password.value;
let confirmPass = repeatPassword.value;
if (pass !== confirmPass) {
console.log("Password don't match. Please try again.");
return false;
} else {
console.log("Password match");
}
}
repeatPassword.addEventListener("keyup", (e) => {
matchTest();
});
};
<div class="form">
<form id="register-form" action="#">
<ul class="form-container">
<li>
<h2>Create Account</h2>
</li>
<li>
<label for="name">Name</label>
<input type="name" name="name" id="name" required />
</li>
<li>
<label for="email" class="emailBox">Email</label>
<input type="email" name="email" id="email" required />
<span class="emailText"></span>
</li>
<li>
<label for="password" class="passBox">Password</label>
<input type="password" id="password" name="password" class="password" required />
<span class="passText"></span>
</li>
<li>
<label for="re-password">Re-Enter Password</label>
<input type="password" id="re-password" name="re-password" class="re-password" required />
</li>
<li>
<button type="submit" class="primary">
Register
</button>
</li>
<li>
<div>Already have an account? Sign-In
</div>
</li>
</ul>
</form>
</div>
I am working on a form validator class in JavaScript.
First, I check (make sure) that all required fields are filled. If they are, I validate the email format:
class FormValidator {
constructor() {
this.hasErrors = false;
this.emptyRequired = [];
this.errorMsg = "";
this.formToValidate = document.querySelector("form");
this.submitButton = this.formToValidate.querySelector("input[type=submit]");
}
appendErrorMessage(){
const errorEl = `<span class="error-message">${this.errorMsg}</span>`;
this.emptyRequired.forEach((field) => {
let parentEl = field.parentElement;
if(this.hasErrors == true && parentEl.querySelectorAll('.error-message').length == 0) {
field.insertAdjacentHTML('afterend', errorEl);
}
});
}
validateEmail() {
this.hasErrors = false;
const re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
const emailFiled = this.formToValidate.querySelector('input[type=email]');
if (this.emptyRequired.length == 0) {
const action = re.test(emailFiled) ? 'remove' : 'add';
emailFiled.classList[action]('is-invalid');
this.hasErrors = re.test(emailFiled) ? false : true;
this.errorMsg = "Please provide a valid email";
this.appendErrorMessage();
}
}
validateRequired() {
this.hasErrors = false;
this.emptyRequired = [];
const requiredFields = this.formToValidate.querySelectorAll('*[required]');
requiredFields.forEach((field) => {
// Make sure all required fields have values
// Before doing other validations
if(!field.value) {
this.hasErrors = true;
this.emptyRequired.push(field);
this.errorMsg = "This field is required";
this.appendErrorMessage();
}
const action = field.value ? 'remove' : 'add';
field.classList[action]('is-invalid');
});
}
validateForm() {
this.validateRequired();
this.validateEmail();
console.log(this.errorMsg);
}
submitForm(e) {
e.preventDefault();
this.validateForm();
}
init() {
this.formToValidate.addEventListener('submit', e => this.submitForm(e));
}
}
const formValidator = new FormValidator();
formValidator.init();
.form-group {
position: relative;
}
.error-message {
margin: 0;
position: absolute;
right: 5px;
bottom: -13px;
color: #a94442;
font-size: 11px;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container">
<div class="card my-3">
<div class="card-header">Contact us</div>
<div class="card-body">
<form action="/" novalidate>
<div class="form-group">
<input type="text" name="name" class="form-control" placeholder="Your Name" value="" required />
</div>
<div class="form-group">
<input type="email" name="email" class="form-control" placeholder="Your Email" value="" required />
</div>
<div class="form-group">
<input type="text" name="phone" class="form-control" placeholder="Your Phone Number" value="" required />
</div>
<div class="form-group">
<textarea name="message" class="form-control" placeholder="Your Message"></textarea>
</div>
<div class="form-group mb-0">
<input type="submit" name="btnSubmit" class="btn btn-success btn-block" value="Send Message" />
</div>
</form>
</div>
</div>
</div>
The problem
I filled all the form fields, including the email. The email I provided is invalid.
For a reason I have not been able to figure out, the message Please provide a valid email is never appended to the <div class="form-group">.
I created a mini application with custom login always in the same page, to explain better I have a main page with the login and registration and when I do the login/registration I remain on the same page and where was the login form appear a "Welcome Back" panel.
The problem is that when I try to reload the page with F5 I get for like 2 seconds the old login form and then appear the "Welcome Back" panel. I've used the If statements of Blaze to manage the check of the current user logged in as we can see:
<template name="login">
{{#if currentUser}}
<div class=" card mb-4 shadow-sm">
<div class="card-header">
<h4 class="my-0 font-weight-normal">Welcome Back</h4>
</div>
<div class="card-body">
TEST
</div>
</div>
{{else}}
<div id="panel-login" class=" card mb-4 shadow-sm">
<div class="card-header">
<h4 class="my-0 font-weight-normal">Login Form</h4>
</div>
<div class="card-body">
<form class="login-form">
<div class="form-group">
<label for="InputEmail">Email address</label>
<input type="email" class="form-control" name="email" id="InputEmailLogin" aria-describedby="emailHelp" placeholder="Enter email">
<small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
</div>
<div class="form-group">
<label for="InputPassword">Password</label>
<input type="password" name="password" class="form-control" id="InputPasswordLogin" placeholder="Password">
</div>
<button type="submit" class="btn btn-primary">Login</button>
<span>or Create an account</span>
</form>
</div>
</div>
<div id="panel-register" class=" card mb-4 shadow-sm">
<div class="card-header">
<h4 class="my-0 font-weight-normal">Register Form</h4>
</div>
<div class="card-body">
<form class="register-form">
<div class="form-group">
<label for="InputEmail">Email address</label>
<input type="email" class="form-control" name="email" id="InputEmail" aria-describedby="emailHelp" placeholder="Enter email">
<small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
</div>
<div class="form-group">
<label for="InputPassword">Password</label>
<input type="password" name="password" class="form-control" id="InputPassword" placeholder="Password">
</div>
<div class="form-group">
<label for="InputPassword">Repeat Password</label>
<input type="password" name="password2" class="form-control" id="InputPasswordConfirm" placeholder="Repeat Password">
</div>
<button type="submit" class="btn btn-primary">Register</button>
<span>or Login</span>
</form>
</div>
</div>
{{/if}}
</template>
That's my JS file where I manage the entire events of login/registration system:
Template.login.events({
'click .register-link': function() {
$('#panel-login').hide();
$('#panel-register').show().addClass("animated fadeIn");
},
'click .login-link': function() {
$('#panel-register').hide();
$('#panel-login').show().addClass("animated fadeIn");
},
// Registration
'submit .register-form': function(event) {
var email = trimInput(event.target.email.value);
var password = trimInput(event.target.password.value);
var password2 = trimInput(event.target.password2.value);
if(isNotEmpty(email) && isNotEmpty(password) && isNotEmpty(password2)
&& isEmail(email) && areValidPasswords(password,password2)) {
Accounts.createUser({
email: email,
password: password,
profile: {
userType: 'Normal'
}
}, function(err) {
if(err) {
sAlert.error("There was an error with the registration, try again!");
} else {
sAlert.success("Account Created! You are now logged in");
}
});
}
// Prevent Submit
return false;
},
// Login
'submit .login-form': function(event) {
var email = event.target.email.value;
var password = event.target.password.value;
Meteor.loginWithPassword(email, password, function(err) {
if(err) {
event.target.email.value = email;
event.target.password.value = password;
sAlert.error("There is an error with your login, try again!");
} else {
sAlert.success("You are now logged in!");
}
})
// Prevent Submit
return false;
}
});
Template.login.helpers({
ifLogged: function(user) {
if(user != null) {
$('#panel-login').hide();
}
}
});
// Trim the input
var trimInput = function(val) {
return val.replace(/^\s*|\s*$/g, "");
};
// Check for empty fields
isNotEmpty = function(value) {
if(value && value !== "") {
return true;
}
sAlert.error('Please fill all the fields');
return false;
};
// Validating Email
isEmail = function(value) {
var filter = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if(filter.test(value)) {
return true;
}
sAlert.error("Invalid email, please use a valid email address");
return false;
};
// Check passwords fields
isValidPassword = function(password) {
if(password.length < 6) {
sAlert.error("Password must be at least 6 characters");
return false;
}
return true;
}
// Check confirmation password
areValidPasswords = function(password, confirm) {
if(!isValidPassword(password)) {
return false;
}
if(password !== confirm) {
sAlert.error("Password do not match");
return false;
}
return true;
};
Here there's a GIF to show you the problem:
https://i.gyazo.com/120efc183793d4d1adc5fb518e01c09c.mp4
Thanks if someone can help me.
If you just wanna to git rid of that flick then you can implement loading on Meteor.loggingIn as sample below, alter it with your use case i.e wrap it in a template Helper and replace that helper with currentUser
if (Meteor.loggingIn()) {
return 'loading';
} else if (Meteor.user()) {
return 'home';
} else {
return 'signin';
}
I'm new to Javascript and I need to validate a log-in form with Bootstrap, the thing is not validating the password in the script.
https://jsfiddle.net/98uqsvu2/
<script type="text/javascript">
function check_info()
{
var user = document.getElementById("inputEmail").value;
var pass = document.getElementById("inputPassword").value;
if(user == "test#gmail.com")
{
if(pass == "123")
{
return true;
}
}
else
{
return false;
}
}
</script>
git: https://gist.github.com/Adaryn/6c38cfafd5e95d8a0bba508a33cebec7
#Adaryn
Since I cannot comment, I posted it as an answer.
I made the following changes to the fiddle and I was able to execute the code.
Removed the link href's from your HTML.
Added the closing body tag.
Moved the script from the javascript code section and pasted it just above the closing body tag.
Here is the updated fiddle.
<div class="container">
<form class="form-signin" form role="form" action="hola.html" name="formlogin" method="post" class="login-form" onsubmit="check_info()">
<h2 class="form-signin-heading">Please sign in</h2>
<label for="inputEmail" class="sr-only">Email address</label>
<input type="email" id="inputEmail" class="form-control" placeholder="Email address" required="" autofocus="">
<label for="inputPassword" class="sr-only">Password</label>
<input type="password" id="inputPassword" class="form-control" placeholder="Password" required="">
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
</form>
</div> <!-- /container -->
<script type="text/javascript">
function check_info()
{
var user = document.getElementById("inputEmail").value;
var pass = document.getElementById("inputPassword").value;
if(user == "test#gmail.com")
{
if(pass == "123")
{
return true;
}
}
else
{
return false;
}
}
</script>
try this code. also added jsfiddle
document.getElementById("submit-form").addEventListener("click", check_info);
function check_info() {
var user = document.getElementById("inputEmail").value;
var pass = document.getElementById("inputPassword").value;
if (user == "test#gmail.com" && pass == "123") {
alert("email and password is valid!!!");
return true;
} else {
alert("email and password is NOT valid!!!");
return false;
}
}
https://jsfiddle.net/damaxrss/