cookies are returning undefined - javascript

So i'm trying a simple cookie exercise and when i hit submit it returns undefined. Also is there a way to check what in a cookie in visual studio code?
function setcookie()
{
var tmr = new Date();
tmr.setDate(tmr.getDate() + 1);
document.cookie = "username="+ document.getElementById("username").innerHTML +";path=/";
document.cookie = "password="+ document.getElementById("password").value +";path=/";
}
function getcookie()
{
var Carray = document.cookie.split(";");
for(i = 0 ; i < Carray.length ; i++)
{
var valuearray =Carray[i].split("=")
if (valuearray == "username")
{
var name = valuearray[1];
}
else if (valuearray == "password")
{
var password = valuearray[1];
}
}
alert("username is " + name +" password is " + password);
}

valuearray will be a array, so you need to check valuearray[0] in the if condition.
var valuearray = Carray[i].split("=")
if (valuearray[0] == "username"){ //Here, valuearray[0]
var name = valuearray[1];
} else if (valuearray[0] == "password"){
var password = valuearray[1];
}

Try this
function getcookie() {
const Carray = document.cookie.split(";");
const [name, password] = Carray.map(item => item.split('=')[1])
console.log("username is " + name +" password is " + password);
}
or if you want to transform your cookies into object use this code
function getcookie()
{
var Carray = document.cookie.split(";");
var cookieObj = Carray.reduce((cookieObj, current) => {
const [key, value] = current.split('=');
return { ...cookieObj, ...{ [key]: value } }
}, {})
console.log("username is " + cookieObj.username +" password is " + cookieObj.password);
return cookieObj;
}
// result
{
username: 'usersname'
password: 'userspassword'
}
Please return your result from the functions, I'm not returning anything because I'm trying to match your code.
and answer to your second question. yes you can get value from vscode but for that you need to start your debugging mode

name and password are declared in the block of for, but you use them in out of the block.
change getcookie function to this:
var name="";
var password ="";
for(i = 0 ; i < Carray.length ; i++)
{
var valuearray =Carray[i].split("=")
if (valuearray == "username")
{
name = valuearray[1];
}
else if (valuearray == "password")
{
password = valuearray[1];
}
}
alert("username is " + name +" password is " + password);

Related

Switch/case keeps storing wrong input when recalling

The error I am seeing that Johnny999 keeps getting stored when the user inputs and loops back to type in that does not contain a number.
async function main() {
let userChoice;
let clientArray = [];
do {
output("1. Create a new profile:\n2. View previous profile:\n3. Quit application:");
let userChoice = await input("Please select an option:");
switch (Number(userChoice)) {
case 1:
//FirstName
let theirName = false;
while (!theirName) {
let firstName = await input("Please enter your first name: ");
theirName = checkName(firstName);
clientArray.push(firstName);
if (!theirName) {
output("Your first name contained numeric. Please re-enter your name without a numeric! ");
} else {
output("Your first name is: " + firstName);
}
}
//LastName
let theirName2 = false;
while (!theirName2) {
let lastName = await input("Please enter your last name: ");
theirName2 = checkName(lastName);
clientArray.push(lastName);
if (!theirName2) {
output("Your last name contained numeric. Please re-enter your name without a numeric! ");
} else {
output("Your last name is: " + lastName);
}
}
//Address
let theirAddress = false;
while (!theirAddress) {
let address = await input("Please enter your address: ");
theirAddress = validateMail(address);
clientArray.push(address);
if (!theirAddress) {
output("Not a valid address: ");
} else {
output("Your address is: " + address);
}
}
//DateOfPurchase
let dateOfPurchase = false;
while (!dateOfPurchase) {
let purchaseDate = await input("Please enter your purchase date YYYY-MM-DD: ");
dateOfPurchase = checkDate(purchaseDate);
clientArray.push(purchaseDate);
if (!dateOfPurchase) {
output("That is not a valid date:");
} else {
output("Your purchase date is: " + purchaseDate);
}
}
//Brand
let theirBrand = false;
while (!theirBrand) {
let brand = await input("Please enter brand of the vehicle: ");
theirBrand = checkBrand(brand);
clientArray.push(brand);
if (!theirBrand) {
output("Is not a valid brand! Please selecta valid brand: ");
} else {
output("Your preferred brand is: " + brand);
}
}
//Model
let vehicleModel = false;
while (!vehicleModel) {
let models = await input("Please choose your model you've selected: ");
vehicleModel = checkMake(models);
clientArray.push(models);
if (!vehicleModel) {
output("Not a brand, please select the right brand: ");
} else {
output("Your preferred brand is: " + models);
}
}
// Client Year
let theirYear = false;
while (!theirYear) {
let clientYear = await input("Please enter car year: YYYY-MM-DD: ");
theirYear = checkDate(clientYear);
clientArray.push(clientYear);
if (!theirYear) {
output("Not a date! No month above 12 or days above 31: ");
} else {
output("Your purchased date input: " + clientYear);
}
}
//VehicleVin
let vehicleVin = false;
while (!vehicleVin) {
let vins = await input("Please enter your VIN: ");
vehicleVin = carVin(vins);
clientArray.push(vins);
if (!vehicleVin) {
output("Must be a valid VIN using only numerical or alphabetic: ");
} else {
output("Your vehicle VIN is: " + vins);
}
}
break;
case 2:
let clientString = "";
for (let i = 0; i < clientArray.length; i++) {
clientString += clientArray[i] + " ,\n";
}
output(clientString)
break;
case 3:
output("Have a good day!");
break;
default:
output("That is not a valid menu choice.");
break;
}
}
while (userChoice != 3);
}
/*------------------------------------------------------------*/
function checkDate(inputValue)
// Take in a string from the user, return true if it is a date in the format YYYY-MM-DD where MM<=12 and DD<=31, and false if it isn't.
{
let outputValue = true;
let inputDate = inputValue.split("-");
// Validate Year
if (!checkYear(inputDate[0])) {
outputValue = false;
}
// Validate Month
if (inputDate[1] < 1 || inputDate[1] > 12 || !Number.isInteger(Number(inputDate[1]))) {
outputValue = false;
}
// Validate Day
if (inputDate[2] < 1 || inputDate[2] > 31 || !Number.isInteger(Number(inputDate[2]))) {
outputValue = false;
}
return outputValue;
}
function checkName(nameCheck) {
let nameValue = true;
const searchName = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"];
for (item of searchName) {
if (nameCheck.includes(item)) {
nameValue = false;
}
}
return nameValue;
}
function validateMail(mailAdress) {
let mailValue = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if (mailAdress.match(mailValue)) {
return false;
} else {
return true;
}
}
function checkBrand(nameCheck) {
let nameValue = false;
const searchName = ["chevrolet", "ford", "gmc", "kia", "bmw", "volvo", "saab", "mitsubishi"];
for (item of searchName) {
if (nameCheck.toLowerCase().includes(item)) {
nameValue = true;
}
}
return nameValue;
}
function checkMake(theirMake) {
let makeValue = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if (theirMake.match(makeValue)) {
return false;
} else {
return true;
}
}
function checkYear(inputValue) {
let outputValue = false;
return Number(inputValue) >= 1900 && Number(inputValue <= new Date().getFullYear());
}
function carVin(inputValue) {
let nameValue = true;
if (inputValue.length != 17) {
nameValue = false;
} else if (inputValue.match("^[A-Z0-9]*$") == null); {
}
return nameValue;
}
Welcome to SO!
It looks like your function is pushing the data to clientArray regardless of the output of the checkName() function, for example. Whatever value the user submits will be added because the output of checkName() is evaluated after the push. Here's one solution:
//FirstName
let theirName = false;
while (!theirName) {
let firstName = await input("Please enter your first name: ");
theirName = checkName(firstName);
if (!theirName) {
output("Your first name contained numeric. Please re-enter your name without a numeric! ");
} else {
clientArray.push(firstName);
output("Your first name is: " + firstName);
}
}
This only pushes the data to clientArray once we know that the name has only valid characters within it.
I also looked through your checkName() function. While your solution is functional, it might be more elegant to check against a regular expression (like in the other functions). I've included a solution for your scenario below.
function checkName(nameCheck) {
let nameValue = /[0-9]+/;
if (nameCheck.match(nameValue)) {
return false;
} else {
return true;
}
}

Below is the javaScript for login validation. but output always "Incorrect username or password" i.e else condition

var objLogin = [{
fname: "sastry",
book: "sastry"
}, {
fname: "laxman",
book: "laxman"
}, {
fname: "visali",
book: "visali"
}]
function storeData() {
var userName = document.getElementById("fname").Value;
var userPasswd = document.getElementById("book").Value;
for (i = 0; i < objLogin.length; i++) {
if (userName == objLogin[i].fname && userPasswd == objLogin[i].book) {
console.log(userName + "Is logged in!!");
return;
} else {
console.log("Incorrect username or password");
}
}
}
When accessing the value of an input field, you should use value (lower case "v").
var userName = document.getElementById("fname").value;
Also, it's great to cache your element references, like this:
const userNameInput = document.getElementById("fname");
const userPasswdInput = document.getElementById("book");
function storeData() {
const userName = userNameInput.value;
const userPasswd = userPasswdInput.value;
for (i = 0; i < objLogin.length; i++) {
if (userName === objLogin[i].fname && userPasswd === objLogin[i].book) {
console.log(userName + "Is logged in!!");
return;
} else {
console.log("Incorrect username or password");
}
}
}
I think there is some typo.
var userName = document.getElementById("fname").Value;
var userPasswd = document.getElementById("book").Value;
As far as I know, document.getElementById("something").value is right;
Oh, someone answer that, but it's my first time to use stack overflow,
how can I do?

Google function returning undefined

I have an issue with a custom google script I'm making to generate a bunch of sheets with info based on other sheets. I can't figure out why this is happening..
I've tried including logs and the values before the return is correct.. however when its returned, I get the value undefined.
it's regarding the function: getTournamentInfo(), called from tournamentInfo = getTournamentInfo(matchInfo[0]);
function getTournamentInfo(abbreviation) {
var sheet = ss.getSheetByName("Tournaments");
var tournaments = sheet.getRange("B2:B").getValues().filter(String);
console.log("Fetching Abbreviation: " + abbreviation);
var r = 2;
tournaments.forEach(function (tournament) {
if (tournament != "")
{
var tInfo = sheet.getRange("B"+r+":K"+r).getValues().toString().split(",");
if (tInfo[0] == abbreviation) {
console.log("Returning Info for: " + tInfo[0]);
return tInfo;
}
}
});
}
function generateSheets() {
var sheet = ss.getSheetByName("Match Schedule");
var matches = sheet.getRange("B5:B").getValues().filter(String);
var r = 5;
matches.forEach(function (match) {
if (match != "")
{
var matchInfo = sheet.getRange("B"+r+":L"+r).getValues().toString().split(",");
if (matchInfo[10] == "true") // Checks wether or not to generate the sheet
{
console.log("Generate = " + matchInfo[10]);
console.log("Fetching Tournament Info: " + matchInfo);
var tournamentInfo = "";
try {
tournamentInfo = getTournamentInfo(matchInfo[0]);
} catch (e) {
console.log(e);
}
console.log(tournamentInfo);
var template = "1v1PlayerTemplate"; // Default Template
if (tournamentInfo[3] == 2) {
template = "1v1TeamTemplate";
} else if (tournamentInfo[3] == 3) {
template = "XvXTeamTaplte";
}
var sheetName = matchInfo[0] + " | " + matchInfo[1];
var matchSheet = ss.getSheetByName(template).copyTo(ss.getSheetByName(template).getParent()).setName(sheetName);
}
}
r++;
});
}```
Your getTournamentInfo function is not returning your result. Your return statement only short-circuits the function supplied in forEach. This is one of the possible solutions (untested):
function getTournamentInfo(abbreviation) {
var sheet = ss.getSheetByName("Tournaments");
var tournaments = sheet.getRange("B2:B").getValues().filter(String);
console.log("Fetching Abbreviation: " + abbreviation);
var r = 2;
let result; // <----
tournaments.forEach(function (tournament) {
if (tournament != "" && result == undefined) { // <-----
var tInfo = sheet.getRange("B" + r + ":K" + r).getValues().toString().split(",");
if (tInfo[0] == abbreviation) {
console.log("Returning Info for: " + tInfo[0]);
result = tInfo; // <----
}
}
});
return result; // <----
}
You can do it more simply with a for loop, instead of forEach:
function getTournamentInfo(abbreviation) {
var sheet = ss.getSheetByName("Tournaments");
var tournaments = sheet.getRange("B2:B").getValues().filter(String);
console.log("Fetching Abbreviation: " + abbreviation);
var r = 2;
for (const tournament of tournaments) { // <==============
if (tournament != "") {
var tInfo = sheet.getRange("B" + r + ":K" + r).getValues().toString().split(",");
if (tInfo[0] == abbreviation) {
console.log("Returning Info for: " + tInfo[0]);
return tInfo;
}
}
}
}

How to make phone numbers displayed through a space

Please, help.
Why are numbers displayed without a space?
How to make phone numbers displayed through a space?
var phoneBook = {};
function re(command) {
if (command.split(" ")[0] == "ADD") {
var name = command.split(" ")[1];
var numb = command.split(" ")[2].split(",");
if (!phoneBook.hasOwnProperty(name)) {
phoneBook[name] = numb;
return phoneBook[name];
} else {
phoneBook[name] = phoneBook[name].concat(numb);
return Object.keys(phoneBook) + ": " + phoneBook[name];
}
}
if (command.split(" ")[0] == "SHOW") {
var book = [];
for (i = 0; i < Object.keys(phoneBook).length; i++) {
var key = Object.keys(phoneBook)[i];
book[i] = [key + ": " + phoneBook[key]];
}
return book;
}
}
re("ADD Ivan 555-10-01,555-10-03");
re("ADD Ivan 555-10-02");
console.info(re("SHOW"));
// ["Ivan: 555-10-01, 555-10-03, 555-10-02"]
var phoneBook = {};
function re(command) {
if (command.split(" ")[0] == "ADD") {
var name = command.split(" ")[1];
var numb = command.split(" ")[2].split(",");
if (!phoneBook.hasOwnProperty(name)) {
phoneBook[name] = numb;
return phoneBook[name];
} else {
phoneBook[name] = phoneBook[name].concat(numb).join(', ');
return Object.keys(phoneBook) + ": " + phoneBook[name];
}
}
if (command.split(" ")[0] == "SHOW") {
var book = [];
for (i = 0; i < Object.keys(phoneBook).length; i++) {
var key = Object.keys(phoneBook)[i];
book[i] = [key + ": " + phoneBook[key]];
}
return book;
}
}
re("ADD Ivan 555-10-01,555-10-03");
re("ADD Ivan 555-10-02");
console.info(re("SHOW"));
Your code works as expected. If you just need the phone numbers printed then get the value of the phone number by accessing it:
var phoneBook = {};
function re(command) {
if (command.split(" ")[0] == "ADD") {
var name = command.split(" ")[1];
var numb = command.split(" ")[2].split(",");
if (!phoneBook.hasOwnProperty(name)) {
phoneBook[name] = numb;
return phoneBook[name];
} else {
phoneBook[name] = phoneBook[name].concat(numb);
return Object.keys(phoneBook) + ": " + phoneBook[name];
}
}
if (command.split(" ")[0] == "SHOW") {
var book = [];
for (i = 0; i < Object.keys(phoneBook).length; i++) {
var key = Object.keys(phoneBook)[i];
book[i] = [key + ": " + phoneBook[key]];
}
return book;
}
}
re("ADD Ivan 555-10-01,555-10-03");
re("ADD Ivan 555-10-02");
//get the full result
console.info(re("SHOW"));
console.info(re("SHOW")[0][0]);

Javascript program keeps outputting wrong index of array

I'm trying to finish an assignment, I'm stuck at and can't find a solution.
Below is my full code.
//Student Object
var student = {
f_name: "",
l_name: "",
s_numb: "",
email: "",
courses: [],
/*This function returns if current object has a specific course
and returns true if it does and false if not.*/
hasCourse: function (course) {
for (var c = 0; c < this.courses.length; c++) {
if (course == this.courses[c]) {
return true;
}
}
return false;
}
};
/*This function returns name with first letter
capitalized and the rest lowercase.*/
function formatingName(name) {
return name.charAt(0).toUpperCase() + name.substr(1, name.length);
}
/*This function validates to match the Student ID pattern and
returns true it matches and false if not.*/
function validateStudentID(sid) {
var patt = /^([0-9]{3}[.]){2}[0-9]{3}$/;
return patt.test(sid);
}
/*This function receives a string array of course codes which
are to be registered for a student. The function returns an empty
string indicating all course codes in the array are valid; otherwise
the function returns the first invalid course code in the array.*/
function validateCourses(courses) {
var error = false;
for (i = 0; i < courses.length; i++) {
if (error == false) {
if (courses[i] != "APC100" && courses[i] != "IPC144" &&
courses[i] != "ULI101" && courses[i] != "IOS110" &&
courses[i] != "EAC150" && courses[i] != "IBC233" &&
courses[i] != "OOP244" && courses[i] != "DBS201" &&
courses[i] != "INT222") {
error = courses[i];
break;
}
}
}
if (error != false) {return error;} else {return "";}
return '';
}
var response = true; //Continues to prompt if error is true
var error = false; //Error flag
var temp_obj = []; //Temporary object that hold current object's values
var temp_course = [];
var students = [];
var x = 0;
while (response == true) {
do {
var str = prompt("Please enter first name, last name, student ID,\nemail and courses (separated by ',')");
if (str == "" || str === null) {
response = false;
break;
}
//Removing white spaces in the string
str = str.split(' ').join('');
//Splitting the string into array by , (coma) and assigning it to temporary object array
temp_obj = str.split(',');
//Validating Student ID
if (validateStudentID(temp_obj[2]) == false) {
alert(temp_obj[2] + " is not a valid student ID, Please use xxx.xxx.xxx format.\nPlease try again!");
error = true;
}
//Validating if student is registered in atleast 1 course.
if (temp_obj.length < 5) {
alert("A student must be registered in at-least 1 course");
error = true;
}
//Checking if student is registered in more than 6 courses
if (temp_obj.length > 10) {
temp_obj = temp_obj.slice(0,9);
}
//Extracting courses from temporary object array
temp_course = temp_obj.slice(4, temp_obj.length);
//Makking all the courses uppercase
for (i = 0; i < temp_course.length; i++) {
temp_course[i] = temp_course[i].toUpperCase();
}
//Validating if courses are valid
if (validateCourses(temp_course) != "") {
alert(validateCourses(temp_course) + " is not the course provided by CPD program!\nPlease try again.");
error = true;
}
}
while (error == true);
//Break out of loop if user submitted nothing or if user pressed cancel
if (response == false) {break;}
//Merging cources array back with temporary object array
temp_obj = temp_obj.concat(temp_course);
//Creating a new instance of a student
students[x] = Object.create(student);
//Assigning values to student object from temporary object;
students[x].f_name = formatingName(temp_obj[0]); //Formatting name
students[x].l_name = formatingName(temp_obj[1]);
students[x].s_numb = temp_obj[2];
students[x].email = temp_obj[3].toLowerCase(); //Making the email all lowercase
//Making the course codes in Uppercase
for (i = 0; i < (temp_obj.length) - 4; i++ ) {
students[x].courses[i] = temp_obj[i + 4].toUpperCase();
}
x++;
}
//Printing total registered students
alert("There are total " + students.length + " students registered.");
var R_fname = [];
var R_lname = [];
var R_sid = [];
var R_email = [];
do {
var no_error = false;
var query = true;
var query_course = [];
while (no_error == false) {
query = prompt("Please enter a course code:");
if (query == "" || query == null) {
query = false;
break;
}
no_error = true;
query_course[0] = query.toUpperCase();
if (validateCourses(query_course) != "") {
alert(query + " is not the course provided by CPD program!\nPlease try again");
no_error = false;
}
}
if (query == false) {break;}
//THIS IS WHERE I THINK THE PROBLEM IS
//THIS IS WHERE I THINK THE PROBLEM IS
//THIS IS WHERE I THINK THE PROBLEM IS
//THIS IS WHERE I THINK THE PROBLEM IS
for (var a = 0; a < students.length; a++) {
//Checking if student is registred in a course
if (students[a].hasCourse(query_course) == true) {
//Assigning values to temporary array.
R_fname[a] = students[a].f_name;
R_lname[a] = students[a].l_name;
R_sid[a] = students[a].s_numb;
R_email[a] = students[a].email;
}
}
var fin_str = "";
//Concatenating all the students in a specific course to fin_str as string.
for (var b = 0; b < R_fname.length; b++) {
fin_str += (R_fname[b] + " " + R_lname[b] + " " + R_sid[b] + " " + R_email[b] + " \n");
}
//Printing list of student in a specific course
alert("List of students registered in " + query + "\n\n" + fin_str);
//Retting temporary arrays
R_fname.length = 0;
R_lname.length = 0;
R_sid.length = 0;
R_email.length = 0;
//Confirms to Exit the query loop
if (confirm("Click 'OK' to continue to query class lists.\nClick 'Cancel' to stop the program.") == false) {break;}
}
while (query != false);
These are the test values:
roy,bean,056.171.486,rbean#example.ca,int222
carl,bell,121.126.536,cbell#example.ca,dbs201,int222
eric,brand,046.123.976,ebrand#example.ca,oop244,dbs201,int222
henry, clay, 034.146.412, hclay#example.ca , ibc233 , oop244 , dbs201 , int222
When the program asks to enter the course code; it is suppose to see if the students have that course and only if they do, it prints that students info.
In my case, even if student does not have the course it still prints it.
Please run the code to see if it makes more sense... I can't explain any better
The problem can be reduced to this:
var Foo = {
courses: []
};
var x = Object.create(Foo);
var y = Object.create(Foo);
x.courses.push(123);
alert(y.courses[0]); // "123"
The reason for this behaviour is that both objects inherit the same prototype and any changes made to .courses will apply to both objects.
For this reason, it would be better to create a constructor function instead:
function Foo()
{
this.courses = [];
}
var x = new Foo();

Categories