Custom event logging multiples - javascript

I wrote a custom Javascript event to handle if username exists among the list of users. when there is no user match, it logs fine that there is no user with that name. but the problem is when there is a user match, both if and else runs simultaneously. the code works like this: user types his username, and as soon as the password field is clicked, an event is fired to check if username exists or not. I am new to Javascript am just trying to figure out custom event thanks.
Below is my code:
var user_list = [
{
username:"john",
name:"john.doe",
last_seen:"2mins ago"
},
{
username:"mary",
name:"Mary marta",
last_seen:"2hrs ago"
},
{
username:"susan",
name:"susy457",
last_seen:"45mins ago"
},
{
username:"moses",
name:"moe23",
last_seen:"45mins ago"
},
];
var password = document.getElementById("passwordtext");
password.addEventListener('click', checkPassword);
//Custom event to grab username field when the user is about to type the password
var users = document.getElementById('usertext');
users.addEventListener('trigger', function(e){
var display = e.target.value;//e.target.value
if(display === ""){
//console.log('empty string..');
}else{
for(var i = 0; i < user_list.length; i++){
if(user_list[i].username === display){
console.log('user found..')
}
else{
console.log('user not found!');
}
};
};
event.preventDefault();
});
function checkUser(){
var event = new CustomEvent('trigger');
users.dispatchEvent(event);
};
function checkPassword(e){
checkUser()
passcode = e.target.value;
//console.log(e.target.value);
event.preventDefault();
};
edit: here is my html form code
<form>
<div class="form-row">
<div class="col">
<input type="text" name="usertext" id ="usertext" class="form-control"placeholder="Email or username"/>
</div>
<div class="col">
<input type="password" id ="passwordtext" class="form-control" placeholder="password"/>
</div>
<div class="col-auto">
<a class="btn btn-primary" id="id-login" href="#" role="button">login</a>
</div>
</div>
</form>

Get your check outside of the for loop. See this example.
However there are even easier ways to do it when you just search your Javascript object for the existence of a user instead of looping the object.
var user_list = [{
username: "john",
name: "john.doe",
last_seen: "2mins ago"
},
{
username: "mary",
name: "Mary marta",
last_seen: "2hrs ago"
},
{
username: "susan",
name: "susy457",
last_seen: "45mins ago"
},
{
username: "moses",
name: "moe23",
last_seen: "45mins ago"
},
];
var password = document.getElementById("passwordtext");
password.addEventListener('click', checkPassword);
//Custom event to grab username field when the user is about to type the password
var users = document.getElementById('usertext');
users.addEventListener('trigger', function(e) {
var display = e.target.value; //e.target.value
if (display === "") {
//console.log('empty string..');
} else {
var userFound = false;
for (var i = 0; i < user_list.length; i++) {
if (user_list[i].username === display) {
userFound = true;
break;
}
};
if (userFound) {
console.log('user found!');
} else {
console.log('user not found!');
}
};
event.preventDefault();
});
function checkUser() {
var event = new CustomEvent('trigger');
users.dispatchEvent(event);
};
function checkPassword(e) {
checkUser()
passcode = e.target.value;
//console.log(e.target.value);
event.preventDefault();
};
<form>
<div class="form-row">
<div class="col">
<input type="text" name="usertext" id="usertext" class="form-control" placeholder="Email or username" />
</div>
<div class="col">
<input type="password" id="passwordtext" class="form-control" placeholder="password" />
</div>
<div class="col-auto">
<a class="btn btn-primary" id="id-login" href="#" role="button">login</a>
</div>
</div>
</form>

Related

(Login page) How to check if a username and a password typed in by the user match with the ones saved in two arrays, using JS?

I am a JavaScript (and an overall programming) newbie, and this is one of my first exercices. I have to do a login page, where the user has to type in an already existing username and password, which are saved in two different arrays (one for the usernames and one for the passwords):
const users=["java", "visual", "personal", "key", "master"]
const passwords=["script", "studio", "computer", "board", "chief"];
Once the user clicks a "submit" button, the website tells him if the login was successful or not (if the credentials typed in exist or not).
The problem is that when the button is clicked, nothing happens: in the code, it should check if the credentials typed in by the user match with the existing ones in the arrays AND with their positions, but it doesn't, and I don't understand why.
The code is pasted below.
JS function:
function login(){
const a=document.getElementById("usn").value;
const b=document.getElementById("psw").value;
for(var i=0; i<users.length; i++){
for(var j=0; j<passwords.length; i++){
if(users.indexOf(a)==passwords.indexOf(b)){
if(users[i].includes(a) && passwords[j].includes(b)){
var suc=document.getElementById("success");
suc.innerHTML="Login successful";
suc.style.backgroundColor="green";
}
else{
var fail=document.getElementById("fail");
fail.innerHTML="Login failed, user not registered";
fail.style.backgroundColor="red";
}
}
else
continue;
}
}
}
HTML (if needed):
<div class="col-md-5 col-sm-6 col-12">
<p class="font title pt-3">Login</p>
<p class="font">Don't have an account yet? <span>Create yours now</span>, it takes just a few seconds.</p>
<div id="fail" class="pt-2 pb-2 ps-1 pe-1 font"></div>
<div id="success" class="pt-2 pb-2 ps-1 pe-1 font"></div>
<br>
<div>
<p class="font">Username</p>
<div>
<input type="text" class="inf pb-3 inf" id="usn" onclick="switchColors()">
</div>
</div>
<br>
<div>
<p class="font">Password</p>
<div>
<input type="text" class="inf pb-3 inf" id="psw" onclick="switchColors()">
<i class="bi bi-eye-slash" id="eye2" onclick="change()"></i>
<i class="bi bi-eye hidden" id="eye1" onclick="change()"></i>
</div>
</div>
<br>
<button type="button" class="btn btn-primary" id="btn" onclick="login()">Login</button>
</div>
</div>
CSS (if needed):
.inf{
border: none;
outline: none;
border-bottom: 1px solid black;
}
.hidden{
display: none;
}
Note: this is an exercise for school to be made ONLY for learning purposes.
Maybe like This:
const users=["java", "visual", "personal", "key", "master"]
const passwords=["script", "studio", "computer", "board", "chief"];
function login(){
const a=document.getElementById('usn').value;
const b=document.getElementById('psw').value;
var inxa = users.indexOf(a);
var inxb = passwords.indexOf(b);
if(inxa < 0){
console.log('Login not found...');
}else if(inxb < 0 || inxa !== inxb){
console.log('Password incorrect...');
}else{ /* (inxa > 0 && inxb > 0 && inxa === inxb) */
console.log('You have successfully logged in');
}
}
<div>Login:</div>
<input type="text" id="usn">
<div>Password:</div>
<input type="text" id="psw">
<br>
<button type="button" onclick="login()">Login</button>
There are so many ways to become the same result. Because you are leaning JS, this is another approach. I'll leave the rest of the code to you for learning ;-)
Note that (passwords[i] == psw) will return true or false
const usn = document.getElementById("usn").value;
const psw = document.getElementById("psw").value;
let success = false;
for (let i=0; i < users.length; i++) {
if (users[i] == usn) {
success = (passwords[i] == psw);
}
}
if (success) {
// login success
} else {
// login failed
}
const users = ["java", "visual", "personal", "key", "master"];
const passwords = ["script", "studio", "computer", "board", "chief"];
function login() {
const username = document.getElementById("usn").value;
const password = document.getElementById("psw").value;
const indexUsername = users.indexOf(username);
const indexPassword = passwords.indexOf(password);
if(indexUsername < 0){
console.log("user not found")
} else if (indexUsername === indexPassword) {
const success = document.getElementById("success");
success.innerHTML = "Login successful";
success.style.backgroundColor = "green";
} else {
const fail = document.getElementById("fail");
fail.innerHTML = "Login failed, user not registered";
fail.style.backgroundColor = "red";
}
}
Note: always try to use explicit names in your variables, functions, etc.

onClick firing multiple times JS

I've created an HTML form with JS validation. I've called the function through a button via onclick but it is firing multiple times resulting in unnecessary blank form data. Here's the code.
I'm pushing the data to firebase realtime db.
I'm new to JS, any help would be appreciated.
HTML
<form class="subscribe-form" id="subscribe-form">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<input class="email-input" name="email" id="email" type="text" placeholder="Email">
</div>
<div class="col-lg-2 col-md-2 col-sm-2 col-xs-2">
<button onclick="updateSubscribeEmail();" class="sitebtn btn-submit"
type="submit">Subscribe</button></div>
</form>
JS
function updateSubscribeEmail() {
// Reference messages collection
var messagesRef = firebase.database().ref("Subscription Emails");
var resetForm = document.getElementById("subscribe-form");
// Listen for form submit
document.getElementById("subscribe-form").addEventListener("submit", submitSubscribeForm);
// Submit form
function submitSubscribeForm(e) {
// To avoid entire page getting refreshed
e.preventDefault();
var email = getInputVal("email");
// Get values
var text;
console.log("Before Validation");
if (email.indexOf("#") === -1 || email.length < 6) {
console.log("After Validation");
text = "Please enter a valid email address!";
red_inner_html.innerHTML = text;
red_div.style.display = "block";
setTimeout(function () {
red_div.style.display = "none";
}, 5000);
} else {
saveMessage(email);
console.log("Before reset");
resetForm.reset();
console.log("after reset");
text = "You have successfully subscribed!";
green_inner_html.innerHTML = text;
green_div.style.display = "block";
setTimeout(function () {
green_div.style.display = "none";
}, 5000);
}
}
// Function to get get form values
function getInputVal(id) {
return document.getElementById(id).value;
}
// Save message to firebase
function saveMessage(email) {
var newMessageRef = messagesRef.push();
newMessageRef.set({
Email: email
});
}
}

form validation and submission not working as expected

I am having an issue with my validation and form submission. Even though it can check the required fields via HTML 5 after pressing the 'Buy Now' button, there are two issues that occur:
1: I can submit the form even though the email field is empty and the javascript validation reflects that. What should happen is that a valid email and matching confirm email must be entered along with the other fields entered for the form is to successfully validated.
2: It does not take the user to the stripe checkout page. The code I have taken from their codebase. If I remove all my validation and click 'Buy Now', it works but not with validation.
<p>
<b>Attach your CV:</b> (.doc, .docx, .pdf, .txt, .rtf)
</p>
<input type="file" id="uploadCV" required/>
<br/>
<br/>
<div class="formcontainer">
<label for="email"><b>Email:</b></label>
<input type="input" id="email" name="email" />
<p id="resultEmail"></p>
<label for="email"><b>Confirm Email:</b></label>
<input type="input" id="confirmEmail" name="confirmEmail" />
<p id="resultConfirmEmail"></p>
<label for="job"><b>Desired Job Position:</b></label>
<input type="input" id="job" name="job" required/>
</div>
<br/>
<p><b>Quantity:</b> 1</p>
<b class="price">Price:</b> £20
<button type="submit" class="btn btn-default buynow" id="checkout-button-sku_xxx" role="link">
Buy Now
</button>
<p class="tcparagraph"><i style="font-size:small">Expected Completion Time: Within 7 working days</i></p>
<p class="tcparagraph">
<input id="field_terms" type="checkbox" required name="terms"> I accept the <u>Terms and Conditions</u></p>
</form>
</div>
</div>
</div>
<!-----------Footer------->
<section id="footer">
<div>
Terms And Condition
Privacy Policy
Cookies Policy
</div>
<p>METIS © 2020 All Rights Reserved</p>
</section>
<script>
var file = document.getElementById('uploadCV');
file.onchange = function(e) {
var ext = this.value.match(/\.([^\.]+)$/)[1];
switch (ext) {
case 'doc':
case 'docx':
case 'pdf':
case 'txt':
case 'rtf':
break;
default:
alert('Please upload a file that matches any of these file types: .doc, .docx, .pdf, .txt, .rtf');
this.value = '';
}
};
function validateEmail(email) {
var 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,}))$/;
return re.test(email);
}
function validate() {
var $result = $("#resultEmail");
var $confirmResult = $("#resultConfirmEmail");
var email = $("#email").val();
var confirmEmail = $("#confirmEmail").val();
$result.text("");
if (validateEmail(email)) {
if (email == confirmEmail) {
$confirmResult.text("");
return true;
} else {
$confirmResult.text("Your email and confirm email do not match");
$confirmResult.css("color", "red");
}
} else {
$result.text("You have not provided a valid email");
$result.css("color", "red");
}
return false;
}
(function() {
var stripe = Stripe('pk_test_xxx');
var checkoutButton = document.getElementById('checkout-button-sku_xxx');
checkoutButton.addEventListener('click', function() {
// When the customer clicks on the button, redirect
// them to Checkout.
const isFormValid = checkoutButton.form.checkValidity();
// if (!isFormValid) return true;
if(validate()==true && isFormValid==true){
stripe.redirectToCheckout({
items: [{
sku: 'sku_xxx',
quantity: 1
}],
// Do not rely on the redirect to the successUrl for fulfilling
// purchases, customers may not always reach the success_url after
// a successful payment.
// Instead use one of the strategies described in
// https://stripe.com/docs/payments/checkout/fulfillment
successUrl: window.location.protocol + '//metis-online.com/services/service-CVREW211392-order-confirmation.php?email=' + $("#email").val(),
cancelUrl: window.location.protocol + '//metis-online.com/order-cancelled',
})
.then(function(result) {
if (result.error) {
// If `redirectToCheckout` fails due to a browser or network
// error, display the localized error message to your customer.
var displayError = document.getElementById('error-message');
displayError.textContent = result.error.message;
}
});
}
});
})();
</script>

How to create multiple login and registration form using JavaScript only and storing to the local server

I need some help I have created a login and registration form and its stores its values to the local storage. This is for a class, how can I make it to accept more than one user. Right now it only takes one username and password.
Thanks in advance,
<!-- sign up form -->
<div class="container pt-5">
<!-- registration form -->
<form id="register-form">
<input id="uName" type="text" placeholder="Name" value="" />
<input id="uPw" type="password" placeholder="Password" value="" />
<input id="rgstr_btn" type="submit" value="get Account" onClick="store()" />
</form>
<!-- login form -->
<form id="login-form" action="./index.html">
<input id="userName" type="text" placeholder="Enter Username" value="" />
<input id="userPw" type="password" placeholder="Enter Password" value="" />
<input id="login_btn" type="submit" value="Login" onClick="check()" />
</form>
</div>
// Name and Password from the register-form
var name = [document.getElementById('uName')];
var pw = document.getElementById('uPw');
// storing input from register-form
function store() {
localStorage.setItem('name', uName.value);
localStorage.setItem('pw', uPw.value);
}
// check if stored data from register-form is equal to entered data in the login-form
function check() {
// stored data from the register-form
var storedName = localStorage.getItem('name');
var storedPw = localStorage.getItem('pw');
// entered data from the login-form
var usrName = document.getElementById('userName').value;
var usrPw = document.getElementById('userPw').value;
// check if stored data from register-form is equal to data from login form
if (userName.value == storedName && userPw.value == storedPw) {
alert('You are logged in ' + usrName);
location.replace("./index.html")
} else {
alert('Access denied. Valid username and password is required.');
}
}
You would want to use an array of objects where each objects stores a username and password. However localStorage only stores strings, so the array needs to be encoded and decoded into a string, which can be done by JSON.
The check function would look like:
function check() {
var usrName = document.getElementById('userName').value;
var usrPw = document.getElementById('userPw').value;
let stored_users = JSON.parse(localStorage.getItem('users'))
if(stored_users) {
for (let u = 0; u < stored_users.length; u++){
if (usrName == stored_users[u].name && usrPw == stored_users[u].password) {
alert('You are logged in ' + usrName);
return location.replace("./index.html");
}
}
} else {
localStorage.setItem('users', '[]');
}
return alert('Access denied. Valid username and password is required.');
}
Then store would look like:
function store() {
var usrName = document.getElementById('userName').value;
var usrPw = document.getElementById('userPw').value;
let stored_users = JSON.parse(localStorage.getItem('users'));
if(stored_users) {
stored_users.push({name: usrName, password: usrPw});
localStorage.setItem('users', JSON.stringify(stored_users));
} else {
localStorage.setItem('users', JSON.stringify([{name: usrName, password: usrPw}]));
}
}
You could store an Object at localStorage instead of property. Just parse it into a JSON string like this:
var users = {
userA: {
name: 'usernameA',
pw: 'passwordA'
},
userB: {
name: 'usernameB',
pw: 'passwordB'
}
};
localStorage.setItem('users', JSON.stringify(users));
Then you can iterate over users object:
var users = JSON.parse(localStorage.getItem('users'));
console.log(users.userA);
console.log(users.userB);
I dont't know the context, I suppose security is not an issue, but I would do something like this:
const jsonObject=localStorage.getItem(key);
//"[{\"user\":\"John\",\"password\":\"12345\"},{\"user\":\"Doe\",\"password\":\"password\"}]"
const theObject=JSON.parse(jsonObject);
// [{user:"John",password:"12345"},{user:"Doe",password:"password"}];
theObject.push ({user:"Jerry",password:"tom"});
const updatedJson=JSON.stringify(theObject);
localStorage.setItem(key, updatedJson);

Contact form variables are not passing into javascript from section tag

Contact form variables are not passing into javascript. basically javascript fail on validation. On debug, I am getting "undefined is not a function." I have several seperators on this page. If i put identical code inside a seperate page like "contact.html" variables pass into javascript.
My understanding is that HTML tag id="contact-form" for some reason does not pass into the function.
Java Script
function code_contactvalidation() {
// Add form.special data (required for validation)
$('form.special input, form.special textarea').each(function() {
this.data = {};
this.data.self = $(this);
var val = this.data.self.val();
this.data.label = (val && val.length) ? val : null;
this.data.required = this.data.self.attr('aria-required') == 'true';
});
// Special form focus & blur
$('form.special input, form.special textarea').focus(function() {
with (this.data) {
console.log('focusing');
if ( label && self.val() == label) self.val('');
else return;
}
}).blur(function() {
with (this.data) {
if ( label && self.val().length == 0 ) self.val(label)
else return;
}
});
// initialize captcha
var randomcaptcha = function() {
var random_num1=Math.round((Math.random()*10));
var random_num2=Math.round((Math.random()*10));
document.getElementById('num1').innerHTML=random_num1;
document.getElementById('num2').innerHTML=random_num2;
var n3 = parseInt(random_num1) * parseInt(random_num2);
$('#captcharesult').attr('value', n3);
$('#buttonsubmit').attr('value','Submit');
};
randomcaptcha();
//initialize vars for contact form
var sending = false,
sent_message = false;
$('#contact-form').each(function() {
var _this = this;
this.data = {};
this.data.self = $(this);
this.data.fields = {};
this.data.labels = {};
this.data.notification = this.data.self.find('.notification');
_.each(['name','email','subject'], function(name) {
_this.data.fields[name] = _this.data.self.find(_.sprintf('input[name=%s]', name));
_this.data.labels[name] = _this.data.fields[name].val();
});
}).validate({
errorPlacement: function() {},
highlight: function(element) { $(element).addClass('invalid'); },
unhighlight: function(element) { $(element).removeClass('invalid'); },
submitHandler: function(form) {
if (sending) return false;
if ( sent_message ) { alert('Your message has been sent, Thanks!'); return false; }
var field, valid = true;
with (form.data) {
_.each(fields, function(field, name) {
if ( $.trim(field.val()) == labels[name] ) { valid = false; field.addClass('invalid'); } else { field.removeClass('invalid'); }
});
}
if (valid) {
sending = true;
$('#ajax-loader').show();
form.data.self.ajaxSubmit({
error: function(errorres) {
$('#ajax-loader').hide();
randomcaptcha();
form.data.notification.removeClass('sucess').addClass('error').find('span:first-child').html('Unable to send message (Unknown server error)');
form.data.notification.animate({opacity: 100}).fadeIn(500);
},
success: function(res) {
sending = false;
$('#ajax-loader').hide();
if (res == 'success') {
sent_message = true;
form.data.notification.removeClass('error').addClass('success').find('span:first-child').html('Your message has been sent!');
form.data.notification.animate({opacity: 100}).fadeIn(500);
$('#formName').val("");
$('#formEmail').val("");
$('#formSubject').val("");
$('#formMessage').val("");
$('#formcheck').val("");
} else if (res == 'captchaerror') {
randomcaptcha();
form.data.notification.removeClass('sucess').addClass('error').find('span:first-child').html('Captcha Error');
form.data.notification.animate({opacity: 100}).fadeIn(500);
} else {
randomcaptcha();
form.data.notification.removeClass('sucess').addClass('error').find('span:first-child').html('Unable to send message (Unknown server error)');
form.data.notification.animate({opacity: 100}).fadeIn(500);
}
}
});
}
return false;
}
});
}
HTML
<section id="contact">
<div class="container">
<div class="row text-center">
<div id="principal" data-align="left">
<div class="form_group_contact">
<script type="text/javascript" src="js/jquery.validate.pack.js"></script>
<script type="text/javascript" src="js/jquery.form.js"></script>
<form class="contactForm special validate" id="contact-form" action="sendmsg.php" method="post">
<p><input id="formName" name="name" type="text" value="Name" class="required" /></p>
<p><input id="formEmail" name="email" type="text" value="Email" class="required email" /></p>
<p><input id="formSubject" name="subject" class="last required" type="text" value="Subject" /></p>
<p><textarea id="formMessage" name="message" class="required margin20" rows="4" cols="83"></textarea></p>
<div class="form_captcha margin20">
<p>Captcha Recognition (<span id="num1"></span> * <span id="num2"></span>) =
<input type="hidden" id="captcharesult" name="captcha_result" value=""/>
<input type="text" class="required number" maxlength="3" size="3" id="formcheck" name="captcha" value=""/>
</p>
</div>
<p class="notification" style="display: none;"><span></span> <span class="close" data-action="dismiss"></span></p>
<p><input type="submit" value="" class="margin20" id="buttonsubmit" /><img id="ajax-loader" alt="" src="./images/ajax-loader.gif" /></p>
</form>
</div>
</div>
</div>
</div>
</section>
if ( label && self.val().length == 0 ) self.val(label)
There needs to be a semicolumn (;) to end that line ;)
Also, you call "each" on the contact-form which makes me think you expect more than one contact-form. You will need to set the identifier as "class" rather than "id" in the HTML and use "." in the jQuery selector rather than "#".
Now you got those little things fixed, please try it out in Firefox. Google is very vague with javascript errors, Firefox will give you a better error message. Please share it with us so I can edit this post with a final solution.

Categories

Resources