how to compare two different length objects in for loop? - javascript

I have tried to create a login function which when the user enters the vaild name and password then it will print "welcome user " else "invalid user".
In my code it accepts one username and password and showing invalid for another one...I cant understand why its showing like this...
code:
<script>
let userName=document.getElementById("input1");
let mailId=document.getElementById("input2");
var out=[{Name:"dhanam",mail:"dhanamram98#gmail.com"},
{Name:"alamelu",mail:"alamu98#gmail.com"}];
function input()
{
var input=userName.value;
var output=mailId.value;
var created=[{Name:input,mail:output}];
return created
}
function output()
{
var inp=input();
for(var i=0;i<inp.length;i++)
{
for(var j=0;j<out.length;j++)
{
console.log(inp[i].Name+inp[i].mail);
console.log(out[j].Name+out[j].mail);
if((inp[i].Name== out[j].Name)&&
(inp[i].mail==out[j].mail))
{
document.getElementById("out1").innerText="welcome
user";
}
else{
document.getElementById("out1").innerText="Invalid
user";
}
}
}
}
var but=document.getElementById("out");
but.addEventListener("click",output);
</script>
find fiddle here:
https://jsfiddle.net/xp1Lrbdh/#&togetherjs=d0wTznLFgu

The issue is because of the iteration you are doing even after finding if entered user is valid user. In simple terms, putting a break statement solves your problem.
See the snippet below:
let userName=document.getElementById("input1");
let mailId=document.getElementById("input2");
var out=[{Name:"dhanam",mail:"dhanamram98#gmail.com"},
{Name:"alamelu",mail:"alamu98#gmail.com"}];
function input()
{
var input=userName.value;
var output=mailId.value;
var created=[{Name:input,mail:output}];
return created
}
function output()
{
var inp=input();
for(var i=0;i<inp.length;i++)
{
for(var j=0;j<out.length;j++)
{
console.log(inp[i].Name, inp[i].mail);
console.log(out[j].Name, out[j].mail);
if((inp[i].Name== out[j].Name)&&(inp[i].mail==out[j].mail))
{
document.getElementById("out1").innerText="welcome user";
break;
}
else{
document.getElementById("out1").innerText="Invalid user";
}
}
}
}
var but=document.getElementById("out");
but.addEventListener("click",output);
NOTE: This is not a best practice to verify credentials also avoid using var, use let, const instead

const accounts = [
{
name:"dhanam",
mail:"dhanamram98#gmail.com"
},
{
name:"alamelu",
mail:"alamu98#gmail.com"
}
]
function output() {
const nameNode = document.getElementById("input1")
const mailNode = document.getElementById("input2")
const name = nameNode.value
const mail = mailNode.value
const found = accounts.find(a => a.name === name && a.mail === mail)
if (found) {
document.getElementById("out1").innerText="welcome user";
} else {
document.getElementById("out1").innerText="Invalid user";
}
}
var but=document.getElementById("out");
but.addEventListener("click",output);

Related

Updating Local Storage

I have a struggle with updating Local Storage values. I have "users" array from which I want to update my Local Storage, buy many problems have occured durning implementation. Please see code below, and also take note its only learning so dont be scared I use local storage for stroing login and password.
class Register {
constructor({
inputLogin,
inputPassword
}) {
this.inputLogin = inputLogin;
this.inputPassword = inputPassword;
}
users = [];
add() {
const btn = document.querySelector('#register-form__submit');
btn.addEventListener('click', (e) => {
e.preventDefault();
const usersData = {
login: this.inputLogin.value,
password: this.inputPassword.value
}
if (localStorage.getItem('users')) {
// // I dont know what to do here, I want to get existing value from local Storage. Put them back to array users and then set local storage with this old an new value... But I've encountered a lot of problems like nested arrays, overlooping etc. Please tell me guys how you would've done it.
} else {
this.users.push(usersData);
localStorage.setItem('users', JSON.stringify(this.users));
}
})
}
}
EDIT: Working solution. I hope it helps sombeody who wants to practice and doesn't know databases yet.
class Register {
constructor() {
this.inputLogin = document.getElementById('login')
this.inputPassword = document.getElementById('password')
this.users = []
}
add() {
//checking if inputs are empty
if (this.inputLogin.value === '' || this.inputPassword.value === '') {
this.alert('Musisz wypełnić wszystkie pola')
} else {
//creating object with users data
let userData = {
login: this.inputLogin.value,
password: this.inputPassword.value,
}
if (window.localStorage.getItem('users')) {
//checking if there are any users in local storage
const existingData = JSON.parse(window.localStorage.getItem('users'));
//looping through those values and checking if there is already such an user with this login.
for (let i = 0; i < existingData.length; i++) {
if (existingData[i].login === userData.login) {
if (document.querySelector('.red-alert')) {
return;
} else {
this.alert("user already exists");
break;
}
} else {
//checking if this.users[] is empty(this happens after refreshing page or restarting browser of course
if (this.users.length === 0) {
existingData.map((obj) => {
return this.users.push(obj);
})
this.users.push(userData);
localStorage.setItem('users', JSON.stringify(this.users))
window.location.href = "index.html";
}
//checking if there is some data in this.users. That means page was not refreshed nor browser was restarted.
else if (this.users.length > 0) {
this.users.push(userData);
localStorage.setItem('users', JSON.stringify(this.users))
console.log(this.users);
window.location.href = "index.html";
}
}
}
}
else {
//success when there are no users at all in this.users[] and local storage is empty
this.users.push(userData);
localStorage.setItem('users', JSON.stringify(this.users))
window.location.href = "index.html";
}
}
alert(text) {
const par = document.createElement('p')
par.classList.add('red-alert');
par.textContent = text;
document.querySelector('.register-form').appendChild(par)
}
}
You need to first check for the existing key and then update the value of the local storage. Have added in line comments for better understanding
// ..rest of the code
// check if the local storage have any key by this na,e
const currStoredData = localStorage.getItem('users');
// if key esxist
if (currStoredData) {
// push the existing value of the key in the array
this.users.push(currStoredData);
// set the new user data in the local storage
localStorage.setItem(usersData)
} else {
this.users.push(usersData);
localStorage.setItem('users', JSON.stringify(this.users));
}
})
You could read the local storage only at the beginning and work with the object after.
Because the storage only saves strings, you need to parse the value as well.
class Register {
constructor({
inputLogin,
inputPassword
}) {
this.inputLogin = inputLogin;
this.inputPassword = inputPassword;
}
users = JSON.parse(localStorage.getItem('users')) || [];
add() {
const btn = document.querySelector('#register-form__submit');
btn.addEventListener('click', (e) => {
e.preventDefault();
const usersData = {
login: this.inputLogin.value,
password: this.inputPassword.value
}
this.users.push(usersData);
localStorage.setItem('users', JSON.stringify(this.users));
})
}
}

Is it possible to add show password functionality in login form of sylius? This script is not working

function myFunction() {
var showpass = document.getElementsByClassName('lpass');
if (showpass.type === "password") {
showpass.type = "text";
} else {
showpass.type = "password";
}
}
This script is not working. In console.log('') it is skipping to else condition directly.
Your var showpass = document.getElementsByClassName('lpass'); returns an array so use the 0 index to get the first match.
var showpass = document.getElementsByClassName('lpass')[0];
You can see more about the function here, https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName

How to check in real time if a user exists in a JavaScript object through an input element (raw js)

I'm quite new to JS and am trying to check if a user or any value exists in a JavaScript object in real time, the goal is to implement this in Firebase in order to prevent user registration if that username has already been taken but I am doing it locally first because Im learning. This is what I have so far.
let input = document.getElementById('input')
let btn = document.getElementById('btn')
btn.disabled = false
let users = [
{
uname: "mark"
},
{
uname: "sarah"
},
{
...others uname
}
]
input.addEventListener('input', () => {
input.value = input.value.replace(regex, "")
check(input.value)
})
function check(val) {
users.forEach((item) => {
let uname = item.uname
if (uname.indexOf(val) > -1 && uname === val) {
console.log('That user name has been taken')
btn.disabled = true
} else {
console.log('Ok')
btn.disabled = false
}
})
}
The problem with that is when I typed in the input element Im getting both the if and else triggered and while (val) matches some key/value pairs the others won't and then I am able to use whatever username Im typing which is not what I want.
How can I solved this? Thanks.
You aren't checking to see if the username has been found.
function isUsernameAvailable (val) {
for (var i = 0; i < users.length; i++) {
var uname = users[i].name;
if (uname === val) {
console.log('That user name has been taken')
btn.disabled = true
return false; // the username is taken, we can stop checking
}
}
console.log('Ok')
btn.disabled = false
return true;
}
Also, forEach doesn't let you exit the loop early and you don't need to check every user after you found a match (if you find a match).

jQuery - Checking if array is empty or has attributes

I'm getting an array of Strings, and if the array has items I want to do one thing and if not I want to do the other. I'm not sure how to check if the array is empty of not. Also when stepping through my code in chrome debugger even if the array has items in it the length is still 0 so I can't use formErrors.length > 0.
Here's my code for getting the errors. This works fine and returns an array of error strings or an empty array:
var formErrors = validateFormData(formData);
function validateFormData(data) {
var errors = [];
if (data["title"].length == 0) {
errors["title"] = "Project title required";
}
if (data["client"].length == 0) {
errors["client"] = "Client name required";
}
if (data["date"].length == 0) {
errors["date"] = "Date required";
} else if (!isValidDateFormat(data["date"])) {
errors["date"] = "Date format invalid - Format: dd/mm/yyyy";
}
if (data["status"] == "") {
errors["status"] = "Please select current status for this project";
}
if (data["type"] == "") {
errors["type"] = "Please select a project type";
}
if (data["extras"].length == 0) {
errors["extras"] = "You must select at least one extra for this project";
}
return errors;
}
Then I want to do one thing if there's no errors and another if there is. But this is the bit that won't work for me.
if (formErrors !== {}) {
displayFormErrors(formErrors);
event.preventDefault();
}
else {
clearForm();
}
I've tried multiple ways and nothing has worked so far. Any help is appreciated, thank you!
EDIT
I can't use the .length on the array cause the length is 0 even when it has data.
Screenshot of chrome debugger
I'm slightly confused about what people are asking sorry, i'm not an expert here is my full code to get a better understanding of what i'm trying to do.
$(document).ready(function () {
$('#submit').on("click", onSubmitForm);
function onSubmitForm(event) {
clearErrorMessages();
var formData = getFormData();
var formErrors = validateFormData(formData);
if (formErrors) {
displayFormErrors(formErrors);
event.preventDefault();
}
else {
clearForm();
// Do other stuff
}
}
function clearForm() {
$('#title').val("");
$('#client').val("");
$('#date').val("");
$('#status').val("planning");
$('#description').val("");
$('.type').prop('checked', false);
$('.extra').prop('checked', false);
$('#title').focus();
}
function clearErrorMessages() {
$(".uk-text-danger").html("");
}
function getFormData () {
var data = [];
data["title"] = $('#title').val();
data["client"] = $('#client').val();
data["date"] = $('#date').val();
data["status"] = $('select#status option:selected').val();
data["description"] = $('#description').val();
if ($("input[name='type']:checked").length > 0) {
data["type"] = $("input[name='type']:checked").val();
}
else {
data["type"] = "";
}
data["extras"] = [];
$.each($("input[name='extras[]']:checked"), function(index, radio) {
data["extras"].push(radio.value);
});
return data;
}
function validateFormData(data) {
var errors = [];
if (data["title"].length == 0) {
errors["title"] = "Project title required";
}
if (data["client"].length == 0) {
errors["client"] = "Client name required";
}
if (data["date"].length == 0) {
errors["date"] = "Date required";
} else if (!isValidDateFormat(data["date"])) {
errors["date"] = "Date format invalid - Format: dd/mm/yyyy";
}
if (data["status"] == "") {
errors["status"] = "Please select current status for this project";
}
if (data["type"] == "") {
errors["type"] = "Please select a project type";
}
if (data["extras"].length == 0) {
errors["extras"] = "You must select at least one extra for this project";
}
return errors;
}
function displayFormErrors(errors) {
for (var field in errors) {
var errorElementId = field + "Error";
$('#' + errorElementId).html(errors[field]);
}
} });
Sorry if this is too much i'm not sure what else to do.
An empty array, string or object is "falsy" in JavaScript.
That is, you can pass the array, string or object directly into the if conditional and it will run depending on if something is in there or not.
if ([]) {
// this will never run
}
if ('') {
// this won't run either
}
if ({}) {
// nor will this
}
var errors = {}; inside the validateFormData function.
And then compare the the object like this.
if (JSON.stringify( formErrors ) !== '{}') { //do something}else { //do something}
Where are you verifying if the formErrors is empty? This verification (the if-else) should be inside the function which submits the form.
Also try using:
if (formErrors.length > 0)
instead of:
if (formErrors !== {})

Issue with Objects in array Javascript

I am having issues searching in an array of objects. Basically what my page needs to do is to create a new "client" using information entered by me, such as Full name, User name, Email and Password. Each one of these clients are objects in an array as you can see below.
var clientlist = [{"username":"John","fullname":"John Doe",
"email":"john.doe#hotmail.com","type":"client","password":"jdoe2"},
This client is already created in my js file, what I need to do is to create a new object to add to this array with this same structure. For example,
var clientlist = [{"username":"Peter","fullname":"Peter Jones",
"email":"peter.jones#hotmail.com","type":"client","password":"pjones1"},
I have written the code but it doesn't work properly, when I run the Firebug I can see that all elements have been added correctly except for the Username which value is "". I cannot seem to search for the username to see if the username that I am adding already exists, it may be a syntax mistake. I will leave my complete code below and thanks in advance for the assistance!.
var clientlist = [{"username":"John","fullname":"John Doe",
"email":"john.doe#hotmail.com","type":"client","password":"jdoe2"},
var Client = {};
function NewClient(){
var found;
var user = $("#username").val();
for (var i = 0; i < clientlist.length; i++) {
if (clientlist[i].username == user) {
found = true;
}else{
found = false;
}
}
if (found == true){
$("#msj").html("User already exists!");
}
else if(found == false){
Client["fullname"] = $("#fullname").val();
Client["username"] = user;
Client["email"] = $("#email").val();
Client["type"] = "client";
Client["password"] = $("#password").val();
clientlist[clientlist.length] = Client;
$("#msj").html("New client has been created");
}
}
Few mistakes that you made:
Forgot to close the clientlist array
Forgot to actually push the newly added client
This code below should work correcting a few mistakes that you made along the way.
var clientlist = [{
"username": "John",
"fullname": "John Doe",
"email": "john.doe#hotmail.com",
"type": "client",
"password": "jdoe2"
}];
function NewClient() {
var found = false;
var user = $("#username").val();
for (var i = 0; i < clientlist.length; i++) {
if (clientlist[i].username == user) {
found = true;
} else {
found = false;
}
}
if (found) {
$("#msj").html("User already exists!");
} else {
var newUser = {
fullname: $("#fullname").val(),
username: user,
email: $("#email").val(),
type: "client",
password: $("#password").val()
}
clientlist.push(newUser);
$("#msj").html("New client has been created");
}
}
Made a fiddle for you:
http://codepen.io/gabrielgodoy/pen/xOxoWw?editors=1011
I guess, you have several issues.
Ending bracket of the clientList
For loop and the found variable
pushing new user to the client list.
I have corrected them and included it below.
<script>
var clientlist = [{"username":"John","fullname":"John Doe",
"email":"john.doe#hotmail.com","type":"client","password":"jdoe2"}]
function NewClient(){
var found=false;
var user = $("#username").val();
for (var i = 0; i < clientlist.length; i++) {
if (clientlist[i].username==user) {
found = true;
break;
}
}
if (found){
$("#msj").html("User already exists!");
}
else{
var newUser={
fullname:$("#fullname").val(),
username:user,
email:$("#email").val(),
type:"client",
password:$("#password").val()
}
clientlist.push(newUser);
$("#msj").html("New client has been created");
}
}
</script>

Categories