Javascript function not working for login - javascript

I am trying to create a very simple login form that requires the user to input a password and a username. If the user does not input a username or a password then i want an alert to pop up informing the user that he needs to input a username or a password and the page will not continue on to the welcome page. however this is not working......i dont get any alert pop up and also i am redirected to the welcome page automatically after i hit 'sign in' i just dont understand what the issue is. Any help would be very much appreciated and thank you in advance.
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Login</title>
<script type = "text/javascript">
function login()
{
var username = document.getElementById("name");
var password = document.getElementById("pass");
if (username.value.trim() == "")
{
alert ("please enter a username or password");
return false;
}
else if (password.value.trim() == "")
{
alert ("please enter a password");
return false;
else
{
true;
}
}
</script>
</head>
<body>
<form onsubmit = "return validate()" action = "welcome.html">
<input id= "name" placeholder= "Username" type= "text"/><br><br>
<input id= "pass" placeholder= "Password" type= "password"/><br><br>
<button type = "submit">SIGN IN</button>
</form>
</body>
</html>

The problem is that on the onsubmit event on the form, you are returning "validate()", which is not a real function.
Instead, replace that bit, in the onsubmit attribute, to onsubmit="return login()", since that appears to be your replacement for the validate function.
Secondly though, in the login function itself, for most browsers you also need to call event.preventDefault(), right before return false (or perhaps instead of). Also, there was a } missing in the login function, also causing an error.
The fixed code should be
function login()
{
var username = document.getElementById("name");
var password = document.getElementById("pass");
if (username.value.trim() == "")
{
alert ("please enter a username or password");
event.preventDefault();
return false;
}
else if (password.value.trim() == "")
{
alert ("please enter a password");
event.preventDefault();
return false;
}
else//this part is also completely extraneous,there's no reason to have it, it should work the same either way
{
true;
}
}
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Login</title>
</head>
<body>
<form onsubmit = "return login()" action = "welcome.html">
<input id= "name" placeholder= "Username" type= "text"/><br><br>
<input id= "pass" placeholder= "Password" type= "password"/><br><br>
<button type = "submit">SIGN IN</button>
</form>
</body>
</html>

Related

Having error in sign up and sign in for blogging websites

First of all, I'm a beginner so, I don't know much but, I expect you would help me.
I've made a website for blogging where you sign up and it redirects you to the main page. Here it should tell me if I already signed up once.
I should get an alert if I have signed up before and it should check pass but, here I am not getting it like that. In fact, it redirects even if I have entered the wrong password for the username.
I don't know why this happens...
Signup.html :
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href= "blog.css">
<meta charset="UTF-8">
<title>Page title</title>
</head>
<body>
<div class="Title" align="center">
<br>
<hr>
<h1> InFinite Blogging</h1>
<hr>
<br>
</div>
</div>
<form id="form" action="signup.html" method="post">
<div class="signup">
<input type="text" id="username" placeholder="username">
<br>
<input type="password" id="password" placeholder="password" >
<button id="next" onclick="check()">sign up </button>
</div>
</form>
<script src="blog.js"></script>
</body>
</html>
Blog.js :
var avail = false;
localStorage.setItem(0, 'admin');
localStorage.setItem('admin', '12345678');
function check() {
var user = document.getElementById('username').value;
var pass = document.getElementById('password').value;
var max1 = Object.keys.length;
var max = Object.keys.length-1;
if( user == "" || user== null || pass ==""|| pass==null ) {
alert("enter your name and password, first.");
document.getElementById('username').focus;
document.getElementById('password').focus;
return false;
} else if(pass.length<8) {
alert("Password must contain 8 characters.");
document.getElementById('username').focus;
document.getElementById('password').focus;
return false;
} else {
for (i = 0; i <= max; i++) {
if (user == localStorage.getItem(i)) {
alert("it looks like you already have account 😃.");
avail=true;
PASS = localStorage.getItem(user);
if (pass!=PASS) {
alert("Please, check your password and write correctly.");
} else if(pass==PASS) {
avail='correct';
}
}
}
if(avail!=true) {
localStorage.setItem(max1, user)
localStorage.setItem(user, pass)
document.getElementById("form").action = 'main.html';
} else if(avail=='correct') {
document.getElementById("form").action = 'main.html';
}
}
}
if(avail == false){
localStorage.setItem(max1, user)
localStorage.setItem(user, pass)
document.getElementById("form").action = 'main.html';}
or
else if(pass==PASS) {
confirmed='correct';
}
There are 2 possible solutions:
check for if(avail == false)
use another variable when the password has been confirmed.
By redeclaring avail = "correct", you are changing the typeof(avail) from boolean to string. Avail will never be true because it's no longer a boolean.

How do I check if input is blank/not blank and do specific thing

Okay so I know this is probably a headache for most of you but i'm having trouble figuring this out as javascript is not my strong suit.
I'm trying to basically get this one page to load if username and password is not blank but if it is blank I want it to alert to me (specifically window.alert()) that I have not inputted username and/or password.
I cannot seem to figure it out so here it is.
<button type="submit" id="enterButton" onclick="newPage()"><strong>Enter</strong></button>
there is my button where I put my function on
var username = getElementById("userName");
var password = getElementById("passWord");
function newPage() {
if(username.val().length==0 || password.val().length==0){
alert("please enter valid information");
return location.href = "newPage.html";
}
else{
location.href = "newPage.html";
}
}
and here is my failed attempt to initialize my idea.
function validateform(){
var name=document.myform.name.value;
var password=document.myform.password.value;
if (name==null || name==""){
alert("Name can't be blank");
return false;
}else if (password==null || password==""){
alert("password can't be blank");
return false;
} else if(password.length<6){
alert("Password must be at least 6 characters long.");
return false;
}
}
<html>
<body>
<body>
<form name="myform" method="post" action="http://www.javatpoint.com/javascriptpages/valid.jsp" onsubmit="return validateform()" >
Name: <input type="text" name="name"><br/>
Password: <input type="password" name="password"><br/>
<input type="submit" value="register">
</form>
</body>
</html>
Try to check first if you can get the value of your username. If you're using plain javascript, you should use document.getElementById("userName").value.

Email validation function not working properly with form button

I am working on my final project for my JS class. I have reached a bit of a roadblock, and was hoping for a little guidance.
I am looking to take the input (all coding needs to be done in JS) for email and validate. If the email is validated, then it should send the input to be written on a new webpage. If the the input is not valid, there should be an alert and the user should then reenter a proper email address.
This is just a portion of the project. I am creating having the user enter input information for a resume to written on the new page.
With the current state of the code, it is popping up the alert box that the email is not valid (even when it is). I have gotten it write if I take away the validation portion. However, it writes "undefined".
//html
<!DOCTYPE html>
<html lan= "en">
<head>
<title>WEB 115 Final Project</title>
</head>
<body>
<script src= "projectJS.js"></script>
<br><br>
<form onsubmit="validateEmail()">
<input type="submit" value="Create Resume">
</form>
</body>
</html>
//JS email
var email = document.createElement("p");
email.innerText = "Enter Email Address:";
document.body.appendChild(email);
var inputEmail = document.createElement("input");
inputEmail.type = "text";
inputEmail.setAttribute("id", "email");
document.body.appendChild(inputEmail);
//email validation on click form button from html
function validateEmail(inputEmail) {
var re = /^[^\s#]+#[^\s#]+\.[^\s#]+$/;
var testRe = re.test(inputEmail);
testRe;
if (testRe != true) {
window.alert("Invalid Email Address. Please Reenter");
}
else {
var openWindow = window.open("");
openWindow.document.write(inputEmail);
}
}
If anybody would be so kind as to advise on this issue, I would be grateful. Thank you.
The issue was simply that you were passing inputEmail as the argument to test() when what you actually want to test is inputEmail.value. Demonstration below should work:
const validateEmail = (e, inputEmail) => {
e.preventDefault();
if (/^[^\s#]+#[^\s#]+\.[^\s#]+$/.test(inputEmail.value)) {
console.log(`${inputEmail.value} is a VALID email address :)`);
return true;
}
console.log(`${inputEmail.value} is an INVALID e-mail address. Please fix!`);
return false;
};
const init = () => {
var email = document.createElement("p");
email.innerText = "Enter Email Address:";
document.body.appendChild(email);
var inputEmail = document.createElement("input");
inputEmail.type = "text";
inputEmail.setAttribute("id", "email");
document.body.appendChild(inputEmail);
document.querySelector('form').addEventListener('submit', e => validateEmail(e, inputEmail));
};
init();
<head>
<title>WEB 115 Final Project</title>
</head>
<body>
<script src="projectJS.js"></script>
<br><br>
<form>
<input type="submit" value="Create Resume">
</form>
</body>
add .value to get Input email like this:
var testRe = re.test(inputEmail.value);
I've solved your problem. Now it's working. Check it.
var email = document.createElement("p");
email.innerText = "Enter Email Address:";
document.body.appendChild(email);
var inputEmail = document.createElement("input");
inputEmail.type = "text";
inputEmail.setAttribute("id", "email");
document.body.appendChild(inputEmail);
//email validation on click form button from html
function validateEmail() {
var inputEmail = document.getElementById('email').value; //get email id
var re = /^[^\s#]+#[^\s#]+\.[^\s#]+$/;
var testRe = re.test(inputEmail);
testRe;
if (testRe != true) {
window.alert("Invalid Email Address. Please Reenter");
}
else {
var openWindow = window.open();
openWindow.document.write(inputEmail);
}
}
<!DOCTYPE html>
<html lan= "en">
<head>
<title>WEB 115 Final Project</title>
</head>
<body>
<script src= "projectJS.js"></script>
<br><br>
<form onsubmit="validateEmail()">
<input type="submit" value="Create Resume">
</form>
</body>
</html>

On Submit, variable that is supposed to change doesn't? Why?

What i am trying to do is when the input is the same as the variable name the user can not press the button 'change' but when the input is different the user is allowed to press the button 'change' and the value name will change but the problem is that the variable is not changing... Why?
Here is the code:
<!DOCTYPE html>
<html>
<head>
<title>App</title>
</head>
<body>
<form id="sendNameForm">
<input id="name" type="text" value="John"/>
<button id="sendNameBtn" type="submit" disabled>Change</button>
</form>
<script src="jquery-1.12.4.js"></script>
<script>
$('#sendNameForm').submit(function() {
var name = $('#name').val();
dis_enableNameSend();
alert("Success!");
return false;
});
var name= $('#name').val();
function dis_enableNameSend(){
var newName = $('#name').val();
if(newName==name){
document.getElementById("sendNameBtn").disabled = true;
}else{
document.getElementById("sendNameBtn").disabled = false;
}
}
$('#name').on('input', function() {
dis_enableNameSend();
});
</script>
</body>
</html>
Thanks!
form submit generally refresh your page by default that may be reason why you do not see change.
try preventing default behaviour
$('#sendNameForm').submit(function(event) {
event.preventDefault()
var name = $('#name').val();
dis_enableNameSend();
alert("Success!");
return false;
});

Onclick event; If and Else

All right so I am doing a javascript code for a login type form and it will lead you to a new page. Here it is:
function submit1()
{
var x=document.getElementById("username");
var y=document.getElementById("password");
if (x.value=="username" && y.value=="password")
{
window.location="Example.php";
}
else
{
window.alert=("The information you have submitted is incorrect and needs to be submitted again!");
}
}
When ever I am hitting the submit button it takes me straight to the page instead of checking to see if it right. Please help!
Thank you in advanced! To let you know this is not a permanet login page!
The easy way to do this would be to use a button input:
<input type="button" value="Check" onclick = "submit1();" />
The alternative is to prevent this default behavior of a submit type input, by making the handler return false. Your HTML would look like this:
<input type="submit" value="Check" onclick = "return submit1();" />
Your function would need to be changed a well (considering the fact that you want it to not redirect). I am assuming you want to preserve data entered, so I am not going to use window.location to redirect. Instead, I am going to allow the form to be submitted:
function submit1()
{
var x=document.getElementById("username");
var y=document.getElementById("password");
if (x.value == "username" && y.value == "password") {
window.alert=("The information you have submitted is incorrect and needs to be submitted again!");
return false;
}
}
<html>
<head>
<title>
Login page
</title>
</head>
<body>
<h1 style="font-family:Comic Sans Ms;text-align="center";font-size:20pt;
color:#00FF00;>
Simple Login Page
</h1>
<form name="login">
Username<input type="text" name="userid"/>
Password<input type="password" name="pswrd"/>
<input type="button" onclick="check(this.form)" value="Login"/>
<input type="reset" value="Cancel"/>
</form>
<script language="javascript">
function check(form)/*function to check userid & password*/
{
/*the following code checkes whether the entered userid and password are matching*/
if(form.userid.value == "myuserid" && form.pswrd.value == "mypswrd")
{
window.location="Example.php"; /*opens the target page while Id & password matches*/
}
else
{
alert("Error Password or Username")/*displays error message*/
}
}
</script>
</body>
</html>
The event needs to cancel the default event and return false. This will prevent the form from submitting.
HOWEVER, it should be a non-issue if the form submits anyway, because JavaScript CANNOT be trusted and therefore you MUST validate all input server-side.
<form method="post" action="." id="myform">
<!-- form contents --->
</form>
<script type="text/javascript">
(function () {
var f = document.getElementById('myform'), // get your form element
x = document.getElementById('username'),
y = document.getElementById('password'),
handler;
handler = function (e) {
e.preventDefault(); // stop submit
if (x.value=='username' && y.value=='password') {
window.location = 'Example.php';
} else {
window.alert('The information...');
}
};
// listen to submit event
if ('addEventListener' in f) {
f.addEventListener('submit', handler, false);
} else { // handle also IE...
f.attachEvent('submit', function () {
handler(window.event);
});
}
}());
</script>
anyway it looks like you're trying to check login/password from JS what is not greatest idea (anyone can just look into source and read it)

Categories

Resources