I've been trying to let javascript redirect to another html file using window.location but it keeps reloading. Here is the Javascript
var myStorage = window.localStorage;
let accounts = [{
username: 'admin',
pass: 'admin123!',
email: 'admin#gmail.com'
}];
myStorage.setItem("account", accounts);
//check login account
var checkLogin = function() {
let uname = document.getElementById("Uname").value;
let pass = document.getElementById("Pass").value;
if (uname == "admin" && pass == "admin123!") {
myStorage.setItem("user", {
username: 'admin',
pass: 'admin123!',
email: 'admin#gmail.com'
});
alert("Login admin");
window.location = "../account/myaccount.html";
alert("redirect");
} else {
myStorage.setItem("user", undefined);
document.getElementById("incorrectAccount").style.color = "red";
document.getElementById("incorrectAccount").innerHTML = "Incorrect Username or Password";
}
};
<form id="login" method="post" onsubmit="return checkLogin();">
<div>
<label><b>Username:
</b>
</label>
<input type="text" name="Uname" id="Uname" placeholder="admin"><br><br>
</div>
<div>
<label><b>Password: </b></label>
<input type="Password" name="Pass" id="Pass" placeholder="admin123!"><br><br>
</div>
<div>
<input type="submit" name="log" id="log" value="Log In"></a>
<span id="incorrectAccount"></span>
<br><br>
</div>
<div>
<input type="checkbox" id="check">
<span>Remember me</span>
</div>
<div>
Forgot Password?
<br><br>
Register
</div>
</form>
After typing the same username and the password, the first alert works and then it skips the redirect link and goes straight for the 2nd alert message
Submitting a form will cause the page to load the URL specified in the action attribute, which defaults to the current URL, which gives that effect though.
You must be trigging the JS when you submit the form. The JS runs, then the form submits, and the URL being navigated to changes.
You need to prevent the default behaviour of the form submission event.
e.g.
var checkLogin = function(event){
event.preventDefault();
and
document.querySelector('form').addEventListener('submit', checkLogin);
Re edit.
This is the problem. However, you are using event binding methods from before they introduced addEventListener (which became a standard in November 2000).
If you want to use intrinsic event attributes (I don't recommend them, they have some confusing gotchas) then you need to return false from the event handler.
onsubmit="return checkLogin();"
You are currently returning the return value of checkLogin, but that doesn't have a return statement so it returns undefined. You need to return false and not any falsy value.
function myRedirect() {
location.replace("https://stackoverflow.com")
}
<button onclick="myRedirect()">Replace document</button>
Related
I am making a login page with validation as part of my school project. Please note: I am aware this is unsecured I just want to get the method correct first then I am going to add a hash function I want to compare the user's input in the form with my default username and password and output an error message if they do not match, or redirect to a different webpage if they both do match.
This is the code I have so far:
<form>
<label for "username"> Username: </label>
<br>
<input type = "text" id = username>
<br>
<label for "password"> Password: </label>
<br>
<input type = "password" id = password>
<br><br>
<input type="submit" value="Submit" onclick = validationFunction()>
<br>
<div id = "error"></div>
<script>
var x = document.getElementById("submit");
x.addEventListener("click", validationFunction());
event.preventDefault()
function validationFunction() {
var inputUsername = document.getElementById(username);
if (inputUsername == "admin") {
} else if (inputUsername != "admin") {
document.getElementById("error").innerHTML = "incorrect username or password";
}
var inputPassword = document.getElementById(password);
if (inputPassword == "password"){
} else if (inputPassword != "password"){
document.getElementById("error").innerHTML = "incorrect username or password";
}
}
event.target.submit();
</script>
</form>
The code works for a second but the page immediately refreshes after showing the output - I am unsure of how to rectify this so that it remains on screen for the user to read and then enter the correct username and password combination.
I am also getting the error:
Uncaught TypeError: Cannot read properties of null (reading 'addEventListener')
for the line:
x.addEventListener("click", validationFunction());
I thought I assigned the variable x to the submit button element, is there anything I need to add?
When you submit a form the default behaviour you get is page refresh. In order to prevent it you need to use the event function preventDefault first thing when you submit it. event.preventDefault().
<form onsubmit="onSubmitFunc(event)">
<input type="text">
<input type="submit">
</form>
function onSubmitFunc(ev) {
ev.preventDefault()
}
I wanna make easy way of page with password.
in javascript when i use any code with "location"(i tried everything.. replace, asign...etc), it didn't work anything!!!!
but instead of location.href, when i used window.open(), it is perfectly working.
but i wanna stay same window... not new tab or new window...
help me...
In Html
<form action="" method="post" name="Please enter the password to continue.">
<div class="WorkPassword">
<input type="password" class="button" id="WorkInputPassword"
name="password" placeholder="Please enter the password"/>
<input type="submit" class="button" id="submit" value="Enter" onClick="goLogin();">
</div>
and in javascript.
var input = document.getElementById( 'WorkInputPassword' );
var goLogin = function () {
var password = input.value;
if (password === '1234') {
location.href="google.com";
return false;
} else {
alert( 'check again' );
input.value = '';
return false;
}
};
If you want to redirect to a new domain you should use the complete address (including the http:// or https://).
location.href="http://google.com";
However in your case it's not enough, since you are inside a submit event of your form, and if you want to cancel that submit event you must use event.preventDefault() inside the function.
So, it should be something like that:
if (password === '1234') {
event.preventDefault();
location.href="http://google.com";
return false;
}
I have a form page that I intend submitting using Ajax. My plan is to
1. Check if email already exists using Ajax
2. Check if passwords match
3. If it does, switch to another "screen" and
4. Submit the form using Ajax
I'm confused because the validate function does not run. It neither switches screens not alerts when passwords do not match. As such, the form does not get submitted either. My code goes below
$('form input:last-child').click(function(e){
e.preventDefault();
var allFields = e.target.parentNode;
function validate () {
if (allFields.elements[3].value !== allFields.elements[4].value) {
return false; // If they don't match, return false
} else {
$('#form-div form').css('left', '-70%');
$('#confirm p').css('margin-left', '-12%'); // else switch screens
}
}
if (validate != false) {
$('#hidden').load("server_script.php"); // `hidden` is a hidden div somewhere on the page
} else
alert ("Passwords do not match");
});
I'm thinking, if they don't match, the rest of the event listener won't run since the false terminates the function from that point on. So I tried making an instance of the validate function outside the event listener and calling it inside the click function but it won't parse because of dependency variables so I'm not sure how to go about this.
UPDATE
Associated HTML attached. (Bonus: the regex pattern does not match 2 or more letters)
<div id=form-div>
<form method=POST action="" >
First Name: <br> <input type=text name=first_name pattern="[a-z]{2,}" required /> <br> <br>
Last Name: <br> <input type=text name=last_name pattern="[a-z]{2,}" required /> <br> <br>
Email: <span id=emailReport></span> <br> <input type=email name=email id=email required /> <br> <br>
Password: <br> <input type=password name=password required pattern=".{6,}" title="Password must be six or more characters" /> <br> <br>
Confirm password: <br> <input type=password name=password required /> <br> <br>
<input type=hidden name=sign_up_date />
<input type=submit value='sign up' />
</form>
<div id=confirm> <p>Some text</p> </div>
</div>
</div>
You forgot to call the 'validate' function.
As it seems by your code you just declared the function without executing him.
The validate function is not being called. Why not simply remove the function definition so the code is part of the click function?
You are not calling the validate function properly
Function calls must have the () i.e. validate() and not validate
$('form input:last-child').click(function(e){
e.preventDefault();
var allFields = e.target.parentNode;
function validate () {
if (allFields.elements[3].value !== allFields.elements[4].value) {
return false; // If they don't match, return false
} else {
$('#form-div form').css('left', '-70%');
$('#confirm p').css('margin-left', '-12%'); // else switch screens
}
}
//if (validate != false) {
if (validate() != false) {
$('#hidden').load("server_script.php"); // `hidden` is a hidden div somewhere on the page
} else
alert ("Passwords do not match");
});
I did a sample code using two templates.Those are :
Login Template - Login Form along with New User Button
Registration Template - Registration Form
Initially shows Login Template.So here when ever clicks a New User! Button in Login Template page then Immediately shows to Registration template page and hiding the Login Template page.In Reregistration Template Page Clicks Registration button if successfully registered then shows to Login Template Page and Hiding the Registration Template Page.I am new to Meteor. So Please see the below code & Suggest me how to do?
HTML Code :
<head>
<title>hcare</title>
</head>
<body>
{{> login}}
</body>
<template name="login">
<form id="login-form" action="action">
<div>
<h2> Login<h2>
<input type="text" id="username" placeholder="Enetr User Name" /><br>
<input type="password" id="pwd" placeholder="Password" /><br>
<input type="submit" value="Login" id="login" />
<input type="submit" value=" New User!" id="register" />
</div>
</form>
</template>
<template name="registration">
<form id="register-form" action="action">
<div>
<h2> Create Account<h2>
<input type="text" id="username" placeholder="Enter UserName" /><br>
<input type="text" id="name" placeholder=" Enter Name" /><br>
<input type="text" id="email1" placeholder=" Enter Email" /><br>
<input type="password" id="pwd1" placeholder=" Enter Password" /><br>
<input type="submit" value="Register" id="register" />
</div>
</form>
</template>
JS Code :
if (Meteor.isClient)
{
Template.login.events
({
'submit #login-form' : function (e,t)
{
// template data, if any, is available in 'this'
console.log("You pressed the button LOGIN ");
e.preventDefault();
// retrieve the input field values
var email = t.find('#email').value
, password = t.find('#pwd').value;
console.log(email);
Meteor.loginWithPassword(email, password, function (err)
{
if (err)
{
console.log(err);
Session.set("loginError", true);
}
else
{
console.log(" Login Success ");
}
});
}
});
Template.registration.events
({
'submit #register-form' : function (e,t)
{
console.log("You pressed the button Register ");
e.preventDefault();
var username = t.find('#username').value
, name = t.find('#name').value
, email = t.find('#email1').value
, password = t.find('#pwd1').value;
console.log("password="+password);
//var email = trimInput(email);
// var isValidPassword = function(val)
// {
// console.log("isValidPassword() "+val.length);
// return val.length >= 6 ? true : false;
// }
console.log("email="+email);
var isValidPassword = function(val, field)
{
if (val.length >= 6) {
return true;
} else {
Session.set('displayMessage', 'Error & Too short.')
return false;
}
}
if (isValidPassword(password))
{
console.log(" *** isValidPassword *** ");
Accounts.createUser({email: email, password : password,username : username }, function(err)
{
if (err)
{
console.log(err);
alert(err.reason);
}
else
{
console.log("Register Successfully");
}
});
}
}
});
}
if (Meteor.isServer)
{
Meteor.startup(function ()
{
// code to run on server at startup
});
}
I would start to add the Meteor Iron-Router package:
https://github.com/EventedMind/iron-router
read the docs and my be my tutorial, too (http://manuel-schoebel.com/blog/iron-router-tutorial).
Then you can easily set up two different routes, one for login and one for register with the Iron-Router.
You can then simply create normal links to switch from /login to /register.
The Iron-Router makes it really much easier, so I would highly suggest to take some time and really understand how it works (it is not that hard).
Good choice to learn Meteor, by the way :-)
To answer your question in your comment:
First of all, you should use the Iron-Router on windows, too. But without it you could render a template depending on the Session.
<body>
{{> content}}
</body>
<template name="content">
{{renderTemplate}}
</template>
Content Helper
Template.content.helpers({
'renderTemplate': function(){
return new Handlebars.SafeString(Template[Session.get('currentTemplate')]({dataKey: 'someValue'})
}
})
Now in the content template should be the template rendered that is in your Session.get('currentTemplate').
You can then simply change the Session variable if someone clicks:
Template.login.events({
'click #register': function(evt, tpl){ Session.set('currentTemplate', 'registration');}
})
Because the Session is a reactive data source and it knows, that the renderTemplate helper method depends on this specific data, it will re run the renderTemplate function. And now the registration template will be rendered.
Also make sure that you set the currentTemplate variable in your clients startup function to 'login'. (Session.set('currentTemplate', 'login'))
Otherwise nothing will show up at first and an error would occur.
This is not tested code, but it should give you a direction... And might even work ;-P
Edit:
You also do not want your input #register button to have the type="submit", make it type="button" so that the form will not be submitted! You can also add to your 'click #register' event-handler this:
evt.preventDefault()
Just to make sure the form will not be submitted.
I was trying to add a second form to a javascript/jquery script that I wrote, however, when i implemented and began testing it, when I would try to send the firm form via a jquery post request, it would instead send a get request. I know that this has to do with the second form, because commenting the script out for the second form makes the site work again. Hopefully a pair of fresh eyes can help!(the loadpage function works as well)
The register function seems to be where the problem is:
//when the user first goes to the page
$(document).ready(function(){
var user = $("#username");
var pass = $("#password");
var submit = $("#submit");
//both of these methods work, I'm not sure if one is better than the other
//$("#submitbutton").click(function(event){
$("#loginform").on('submit', function(event){
event.preventDefault();
$('.loginerror').remove();
$.post("login.php", {username:user.val(), password:pass.val()}, function(data){
if(!data)
{
$("#login").append("<h3 class='loginerror'>Incorrect Username or Password</h3>");
}
else
{
loadpage();
}
}, "json");
});
//if the user clicks the username prompt him with the login div
$("#registerbutton").click(function(event){
register();
});
});
function register()
{
$("#login").hide("slow");
$("#registerdiv").css("display", "block");
//initiate some variables
var regusername = $("#regusername");
var reg1password = $("#reg1password");
var reg2password = $("#reg2password");
var regemail = $("#regemail");
var regfirstname = $("#regfirstname");
var reglastname = $("#reglastname");
//TODO: check to make sure form is filled out properly
$("#registerform").on('submit', function(event){
event.preventDefault();
//send post request
$.post("register.php", {regusername:regusername.val(), password1:reg1password.val(), password2:reg2password.val(), email:regemail.val(), firstname:regfirstname.val(), lastname:reglastname.val()}, function(data){
if(!data)
$("#registerdiv").append("<h3> class='loginerror'>Server error, retry</h3>");
else
$("#registerdiv").hide("slow");
$("#loginiv").slidedown("slow");
}, "json");
}
And here's the HTML with the two forms:
<body>
<Div id="welcome"> Welcome </div>
<Div id="login">
<br><br><h2>Welcome to QuotesLib</h2>
<br><br><br><form id="loginform"> Username:
<input type = "text" name = "username" id ="username"> <br> Password:
<input type = "password" name = "password" id = "password"> <br>
<input type = "submit" name="submitbutton" id="submitbutton" class = "bluebutton">
</form>
<form><br><br><br>Don't have an account yet?<br><button id="registerbutton" name="registerbutton" href="register.html">Register Now</button>
</Div>
<Div id="registerdiv">
<br><br><h2>Sign Up For QuotesLib</h2>
<br><form id="registerform"> Username:
<input type ="text" id="regusername"> <br> Password:
<input type ="password" id="reg1password"> <br> Repeat Password:
<input type ="password" id="reg2password"> <br> First Name:
<input type ="text" id="regfirstname"> <br> Last Name:
<input type ="text" id="reglastname"> <br> email:
<input type ="text" id="regEmail"> <br>
<input type ="submit" id ="registersubmitbutton">
<br> </form>
</Div>
It would be super helpful if someone could give me an answer to this question!
$("#registerdiv").append("<h3> class='loginerror'>Server error, retry</h3>");
should be
$("#registerdiv").append("<h3 class='loginerror'>Server error, retry</h3>");
see the difference:
<h3>... and <h3 ...
The code has some mistakes,
first,
<form><br><br><br>Don't have an account yet?<br><button id="registerbutton" name="registerbutton" href="register.html">Register Now</button>
You are having a form open tag but not a close tag, the form tag even not needed for this button, and that was the main reason for the problem
second, the end of the JS code,
}, "json");
}
should be
}, "json");
});
}
I'm not sure whether you missed while copying,
Third,
The <h3> tag within the append method, though it is not the matter for the problem you are having.
It is better to use some text editors which hi-lights the code open, end tags, braces.
Here the working code