If Statement Not Acting As Expected - javascript

$(document).ready(function(){
logger();
});
function logger()
{
if(localStorage.getItem("status") === null)
{
$("#test").html("Not logged in.");
$("#buttonlogin").click(function(){
var ul = $("#userlogin").val();
var pl = $("#passlogin").val();
$.post("includes/logger.php", {type : "login", user : ul, pass : pl}, function(dlogin){
if(dlogin == 1)
{
$("#outlogin").html("Please enter a username.");
$("#userlogin").focus();
}
else if(dlogin == 2)
{
$("#outlogin").html("Please enter password.");
$("#passlogin").focus();
}
else if(dlogin == 3)
{
$("#outlogin").html("This username doesn't exist.");
$("#userlogin").focus();
}
else if(dlogin == 4)
{
$("#outlogin").html("This username and password don't match.");
$("#userlogin").focus();
}
else
{
localStorage.setItem("status", dlogin);
logger();
}
});
});
$("#buttonregister").click(function(){
var ur = $("#userregister").val();
var pr = $("#passregister").val();
var cpr = $("#confirmpassregister").val();
$.post("includes/logger.php", {type : "register", user : ur, pass : pr, cpass : cpr}, function(dregister){
if(dregister == 1)
{
$("#outregister").html("Please enter a username.");
$("#userregister").focus();
}
else if(dregister == 2)
{
$("#outregister").html("Please enter a password.");
$("#passregister").focus();
}
else if(deregister == 3)
{
$("#outregister").html("Please enter a confirm password.");
$("#cpassregister").focus();
}
else if(dregister == 4)
{
$("#outregister").html("Password and confirm password do not match.");
$("#passregister").focus();
}
else if(dregister == 5)
{
$("#outregister").html("This username is already taken.");
$("#userregister").focus();
}
else
{
localStorage.setItem("status", dregister);
logger();
}
});
});
}
else
{
$("#test").html("You are logged in.");
$("#buttonlogout").click(function(){
localStorage.removeItem("status");
logger();
});
}
}
The above code is meant to check whether or not a localStorage variable is in existence or not. If it is then only allow the log out button to be pressed. If is doesn't then let the two forms to work. Once it is done with either it is supposed to recheck if the variable is set and then do as I said above. However it ignores it when a user logs in and allows the forms to run. If you refresh however it works fine. I cannot for the life of me figure out why this is happening, and it is beginning to piss me off. Any help would be appreciated.

On your else statement, try adding:
$('#buttonlogin').unbind('click');
$('#buttonregister').unbind('click');
If I understand your problem correctly, what's happening is those events are registered when you first run $("#buttonlogin").click(function()....
It doesn't matter that you call logger() again and the if statement is false the second time around. If you want to disable these callbacks you have to do it explicitly.

Related

JavaScript Multiple Entry Form Validation

I am trying to use Javascript to validate user input before page redirects.
Users can either Input Student ID, Name, or Gender, and based on their input, they will be redirected to a URL.
However, I don't seem to get the multiple entries correctly in my javascript and nothing happened when the submit button is clicked.
I have tried different solutions which I found here.
see my JavaScript code below;
var attempt = 3; // Variable to count number of attempts.
// Below function Executes on click of login button.
function validate(){
var username = document.getElementById("studentid").value;
if ( studentid == "12345" || studentid == "Daniel" || studentid == "Boy"){
alert ("Correct Input");
window.location = "https://www.google.com";
// Redirecting to other page.
return false;
}
else{
attempt --;// Decrementing by one.
alert("ATTENTION!\nInvalid student ID!\nNot associated with any student\nYou have left "+attempt+" attempt;");
// Disabling fields after 3 attempts.
if( attempt == 0){
document.getElementById("studentid").disabled = true;
document.getElementById("submit").disabled = true;
return false;
}
}
}
I have tried to use the solutions below;
if ( studentid == "#12345, #Daniel, #Boy"));{
alert ("correct input");
window.location = "https://www.google.com";
// Redirecting to other page.
if ( studentid == '12345', 'Daniel', 'Boy'){
alert ("correct input");
window.location = "https://www.amazon.com";
// Redirecting to other page.
After so many attempts, I finally got it right!
var attempt = 3;
function check(form)
{
if(form.studentid.value == "12345" || form.studentid.value == "DANIEL" || form.studentid.value == "BOY")
{
window.location.replace('https://www.google.com')
return false;
}
else
{
attempt --;// Decrementing by one.
alert("ATTENTION!\nInvalid student ID!\nNot associated with any student!\nYou have left "+attempt+" attempt;");
// Disabling fields after 3 attempts.
if( attempt == 0){
document.getElementById("studentid").disabled = true;
document.getElementById("submit").disabled = true;
return false;
}
}
}

i am trying to create a simple login page using javascript that will allow the user to input their username and password correctly until 3 tries ONLY

i am new to javascript and i was not able to figure out how to do it correctly. i was trying to create a simple page that will allow the user to input their username and password correctly but if they enter an invalid username or password 3 times, they won't be allowed to input again.
here is my code:
var UserInfo=[
{
username:"elliot",
password:"123"
},
{
username:"nicholas",
password:"456"
},
{
username:"rose",
password:"789"
},
{
username:"samantha",
password:"987"
},
{
username:"austin",
password:"654"
}
]
document.getElementById("btn").onclick=function(){
var username=document.getElementById("un").value
var password=document.getElementById("pw").value
for(i=0;i<4;i++){
if (username==UserInfo[i].username && password==UserInfo[i].password){
alert("Successfully logged in!");
}else{
alert("Please try again.");
}
}
}
You cannot use for loop for that. You need a counter to count how many attempts and increase that counter every time the user makes a mistake. Try something like this:
let attempts = 0
document.getElementById("btn").onclick=function(){
var username=document.getElementById("un").value
var password=document.getElementById("pw").value
if(attempts>=3){
alert("Sorry. Too many attempts.");
}
else{
if (UserInfo.find(el=> el.username === username && el.password === password)){
alert("Successfully logged in!");
}else{
attempts++
alert("Please try again.");
}
}
}

Javascript doesn't follow top to bottom convention

btnsubmit.addEventListener('click', e => {
const task = txttask.value;
const description = txtdescription.value;
const date = txtdate.value;
firebase.auth().onAuthStateChanged(firebaseUser => {
if (firebaseUser) {
console.log(firebaseUser.email)
firebase.database().ref('uid/' + firebaseUser.uid + '/reminders/' + date).set({
task: task,
description: description,
date: date,
});
alert('Data Has Been Recorded');
}
});
document.getElementById("input_form").reset();
so when I hit the submit button I get the alert but the data is not saved.
another example
if (firebaseUser) {
console.log(firebaseUser);
return window.location.href = 'index.html';
} else {
if (email == '' && pass == '') {
alert('Please Enter The Email and The Password!')
} else if (pass == '') {
alert('Please Enter The Password!')
} else if (email == '') {
alert('Please Enter The Email')
}
else {
if (firebaseUser) {
console.log(firebaseUser);
return window.location.href = 'index.html';
} else {
alert('Something went wrong')
}
}
console.log("not loged in");
}
});
Here the website shows the alert that something went wrong and when I clear it I'm logged in. I added extra if to again check if the user exists just in the case. but it still does that, so I'm confused as to what am I doing wrong in both scenarios.

Form click function to check variable before submitting

I am using a $.get function to check the connection to the server before submitting the ASP login form. If the get function is successful and returns a true then the form should submit, otherwise if it fails and returns false, it should not.
I have tried many different configurations, but everything I've tried has either rendered the button inoperable, or only showing a true, and never a false!
Any advice is appreciated. Thanks.
<asp:Button ID="LoginButton" runat="server" CommandName="Login" Text="Enter" ValidationGroup="LoginUserValidationGroup" class="submitButton" />
UPDATE - The code below executes the get function correctly, but I have a feeling the problem lies within $('form').submit();
When true is returned the page refreshes like it sent the data, but the system does not log the user in. Why is this!?
submitButton.click(function () { // capitalize username on login
var url = 'https://examplesite.com/';
$.get(url).done(function () {
if (usernameBox.val() === '') {
usernameBox.attr('placeholder', 'Username Required');
passwordBox.attr('placeholder', '');
usernameBox.focus();
return false;
}
else if (passwordBox.length && passwordBox.val() === '') {
passwordBox.attr('placeholder', 'Password Required');
usernameBox.attr('placeholder', '');
passwordBox.focus();
return false;
}
else if (passwordBox.length && passwordBox.val().length < 6) {
passwordBox.focus();
return false;
}
else {
alert('Successful - Now logging in');
$('form').submit();
}
}).fail(function () {
alert('Failed - No Connection');
});
return false;
});
};
$.get is an async function, so online is never set to what you think it is since the rest of the code is being processed before the call is complete. Move your logic into the .done part of it!
$.get(url).done(function () {
online = true;
if (online == true) {
alert('Success');
$('form').submit();
}
else if (online == false) {
alert('Cannot Connect');
return false;
}
else {
return false;
}
}).fail(function () {
online = false;
});

Can I wait for $.get() call before submitting the form?

I have a sign-up form which prompts for the first name, last name, username, password and e-mail address. I'm using two separate $.get() methods to check if the username and e-mail address are not existing.
This is my function:
function validateSignUp() {
var firstName = $("#first-name").val();
var lastName = $("#last-name").val();
var username = $("#username").val();
var password = $("#pass").val();
var email = $("#email").val();
var passwordVerifier = $("#retype-pass").val();
var emailVerifier = $("#retype-email").val();
errorMessage = "";
var isUsernameValid = validateUsername(username);
var isError = false;
// validate first name field
if (firstName == "" || lastName == "") {
isError = true;
$("#error-message").html("All fields are required");
}
// validate password
if (validatePassword(password) == false) {
isError = true;
$("#check-password").html("Password is invalid");
}
else {
$("#check-password").html("");
}
// validate password verifier
if (passwordVerifier == password) {
if (validatePassword(passwordVerifier) == false) {
isError = true;
$("#recheck-password").html("Minimum of 6 characters and maximum of 30 characters");
}
else {
if (password != passwordVerifier) {
isError = true;
$("#recheck-password").html("Minimum of 6 characters and maximum of 30 characters ");
}
else {
$("#recheck-password").html("");
}
}
}
else {
isError = true;
$("#recheck-password").html("Passwords didn't match");
}
// validate username field
if (isUsernameValid == false) {
isError = true;
$("#check-username").html("Alphanumeric characters only");
} // if
else if (isUsernameValid == true) {
$.get("/account/checkavailabilitybyusername", { username: username },
function(data) {
if (data == "Not Existing") {
$("#check-username").html("");
}
else if (data == username) {
isError = true;
$("#check-username").html("Sorry, this username is already registered");
}
}
);
} // else
// validate e-mail address field
if (validateEmail(email) == false) {
isError = true;
$("#check-email").html("Sorry, the e-mail you typed is invalid");
} // if
else if (validateEmail(email) == true) {
$.get("/account/checkavailabilitybyemail", { email: email },
function(data) {
if (data == "Not Existing") {
$("#check-email").html("");
}
else if (data == email) {
isError = true;
$("#check-email").html("Sorry, this e-mail is already registered");
}
});
}
if (isError == true) {
return false;
}
return true;
}
When other fields are blank and the username and/or e-mail address is existing, the form is not submitted. And the callback functions of the get methods are called as well. But when I'm going to submit my form with no empty fields, it is automatically submitted without checking the username and/or e-mail by $.get(). Is there anything wrong with my function or I'm not yet discovering something. Thanks.
You need to use a full ajax() call and set the async property to false. This makes your request synchronous, i.e. it forces the browser to wait until doing anything else. Try this:
$.ajax({
url: "/account/checkavailabilitybyemail",
data: { email: email },
async: false,
success: function(data) {
if (data == "Not Existing") {
$("#check-email").html("");
} else if (data == email) {
isError = true;
$("#check-email").html("Sorry, this e-mail is already registered");
}
})
});
if (isError == true) {
return false;
}
I suggest you leverage Jquery validate with two remote rules. It's quite easy to implement and a very mature plugin. This way you can focus on other aspects of your UX and not have to re implement this validation logic should you need to validate another form in your project.
Inside your main function, you cannot directly wait for the $.get() to return. But you can move the form submission to the success callback of the AJAX call (assuming form to contain a reference to the actual form element):
$.get("/account/checkavailabilitybyusername", { username: username },
function(data) {
if (data == "Not Existing") {
$("#check-username").html("");
form.submit();
//--------------------------^
}
else if (data == username) {
isError = true;
$("#check-username").html("Sorry, this username is already registered");
}
}
);
Note however, that then the form submission depends on the AJAX to return. Most useful would be a timeout (with window.setTimeout()) and a server-side validation, if the JS doesn't respond or the user has JS disabled.

Categories

Resources