Issue with passing property through function - javascript

First off my apologies if I did something incorrectly with asking a question, I'm very new to stackoverflow and javascript as well. I am having an issue with passing a property through my getPassword function and I've searched around and couldn't truly pinpoint an answer. The code I created is designed for an object called "student" with two properties; FirstName and LastName.
Using a couple of dialogue boxes the information related to each student is entered. At the end, a prompt should display and asks the user "Do you want to add more student?" If the answer is "Yes", It asks the next student's information. If the answer is anything else, It stops asking. Then the information is displayed on the webpage. I want to have a property called "UID" The format of UID is FirstName_PSWD. For calculating the "PSWD" the function called "generatePassword" is used. This function randomly creates a 6-digit password including characters and numbers. For example: if username is John, then UID may be "John_X12bn231". I can not seem to get this password function to work, what might I be doing wrong? I am also aware that there might be other errors in my code, which I do apologize for i am very much a beginner.
var student={FirstName:"", LastName:""};
var studentlist=[];
var i=0;
function generatePassword() {
var length = 4,
charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",
retVal = "";
for (var i = 0, n = charset.length; i < length; ++i) {
retVal += charset.charAt(Math.floor(Math.random() * n));
}
return retVal;
}
function Register() {
var next="Yes";
while (next="Yes"){
student.FirstName=prompt("Please enter the name");
student.LastName=prompt("Please enter the last name");
studentlist.push(student);
document.getElementById("demo").innerHTML += "<li> <b>First Name:</b> "+ studentlist[i].FirstName + "," +
"<b>Last Name: </b>"+ studentlist[i].LastName + "," + "</li>";
next = prompt ("Do you want to add more data?", "Yes")
i++;
}
}

Two mistakes:
var student={FirstName:""; LastName:""};
Should be -> var student={FirstName:"", LastName:""};
var i==0; -> var i = 0;
Try after changes and tell me if it works ;d
Btw. Javascript is a frontend. Your users will be able to check how you generate the password, because all your code can be read.

Related

Search for string between two characters if next to a specific string

I am in need of some modification to my function to allow for a search of two strings on one line of a value. I am trying to work through this on my own but I need some help. Here is an example of a cell value being looked at. Assume there are no leading or trailing newlines. Also, all the cells have the same format. same number of lines, same structure of membertype: last, first etc.
Say I want to see if this cell contains a team lead with the name of last2 or a Manager with the name first4. Both the type of employee and name would be user inputted.
I tried using the following that I created with the help of this.
indexOf(':(.*):')
It returns the position of the content between and including the colons. Then I tried the following:
flatUniqArr[0].search('Supervisor:')
This is where I'm stuck. It returns the index to the last digit of the first line.
My thought was to do a search of the user inputted name between the colons if they follow the user inputted member type. How can I accomplish this?
Clarifications:
The end goal is to verify that the name and member type are on the same line and excluded from an array I am building for .setHiddenValues(). So if they are on the same line exclude from list.
Here is the function I will be adding it to:
var flatUniqArr = colValueArr.map(function(e){return e[0].toString();})
.filter(function(e,i,a){
return (a.indexOf(e) == i && !(visibleValueArr.some(function(f){
return e.search(new RegExp(f,'i')) + 1;
})));
});
return flatUniqArr;
Where flatUniqArr is the list of hidden values. colValueArr is the array of values from a column. visibleValueArr is the name which is user inputted and memberType will be the member type.
Attempts using Liora's solution: (Updated... Works now)
var flatUniqArr = []
var lines = []
Logger.log(visibleValueArr)
Logger.log(memberType)
for (var i = 0; i < colValueArr.length; i++){
lines = colValueArr[i].toString().split('\n');
var found = false;
for(var j = 0; j < lines.length; j++){
var data = lines[j].toLowerCase().split(':')
if(data[0] == memberType.toString().toLowerCase() && data[1].indexOf(visibleValueArr.toString().toLowerCase()) != -1){
found = true;
}
}
Logger.log(found)
if(found == false){flatUniqArr.push(colValueArr[i])}
}
return flatUniqArr;
It works now. It seems like a lot of code though. I'd be open to alternative solutions if they are faster and/or less lines of code.
Updated: Added .toString().toLowerCase() as the user may input lowercase values.
I assume all the line have this format.
If you split each line with the separator ":"
var array = value.split(":")
Then you'd have
array[0] //the current role
array[1] //the list of name
array[2] //the email
And you can check each names then
if(array[0] == "Team Lead" && array[1].indexOf("last2") != -1)
An example with a linesplit:
var lines = value.toString().split("\n");
var found = false;
for(var i = 0; i < lines.length ; i++){
var data = value.split(":")
if(data[0] == "Team Lead" && data[1].indexOf("last2") != -1){
found = true;
}
}
How about just building the regex using the user input?
function search(line, employeeType, employeeName) {
var regexp = '/' + employeeType + ': ' + employeeName + '/'
return line.search(regexp)
}
Or better yet, if it always occurs at the beginning of the string, just use startsWith()

Trying to generate username Javascript

Before I start I should mention i'm a complete novice and I apologise if this code is horrific.
I'm trying to create a username using first initial and surname to be ouputted with a welcome message of "hello Username, welcome to myfunction!".
I'm suppose to use a string to attach the initial and surname together then concatenate the first character of string 1 with string 2 and store the username.
any help would be appreciated as this is for school.
here's what I have so far...
<!DOCTYPE html>
<script type = "text/javascript">
// GenerateUsername Function
function GenerateUsername ()
{
var x;
var firstInitial = prompt("Please enter your initial of your first name");
var surName = prompt("please enter your surname");
var user = new Array();
firstInitial [0] = "user";
surName [1] ="user";
document.write(firstInitial + surName);
}
if (user == 0)
{
alert("welcome, " + user);
}
</script>
I think this might can help you. return value from function call and then bind in alert
function GenerateUsername ()
{
var x;
var firstInitial = prompt("Please enter your initial of your first name");
var surName = prompt("please enter your surname");
var user = new Array();
firstInitial [0] = "user";
surName [1] ="user";
return firstInitial[0] + ' ' + surName[1];
}
if (user == 0)
{
alert("welcome, " + GenerateUserName());
}
if you want to call your function when your page is loaded you have to add the attribute onload="GenerateUsername()" on a html tag.
Also you should place your javascript in a different file and comment your code (it is easy to understand it but if you're a total beginner in javascript you will probably not remember what's the difference between prompt and alert in some days for example).

Javascript: Storing and Sorting Data with Arrays

I am a beginner and I need help with this programming assignment.
Need to do a prompt. Get 10 names as input from user (string inputs). Put the names into an array and then write it out to the webpage.
My question is how do I save the input in the array, when the prompt has to be displayed over and over again for each name the user enters a name? Also, depending on how many names the user wants to enter, the user has a choice of quitting the prompt by typing in the letter 'q'. I am quite proficient at coding while and for loops, but not so much at coding arrays. Tried to search online but couldn't find an answer.
I would love if somebody could explain how to do it. Thanks!
I suggest the following solution:
// Create new array with 10 default values:
var result = new Array(10).fill('');
// Fill array with names via prompt():
eval(((a, b = ['x => x' + '.' + '\n' + 'so\x6De']) => b + '\x28' + a + '\x29')((a, b) => 'q' == (x[b] = prompt())))(result);
// Print result:
console.log(result);
How about something like this?
in your html somewhere
<div id="names">
</div>
function getNames(num) {
var arr = [],
person,
max = num || 5; // number of names you want
return (function R() {
if (arr.length < max) {
person = prompt("Please enter your name");
arr.push(person)
R()
} else {
document.getElementById("names").innerHTML =
"Hello " + arr.join(", ") + "! How are you today?";
}
}())
}
getNames(4)

Javascript assignment for school involving objects and Validation not working correctly

the past two days I've been really struggling on finishing this assignment.
The assignment goal is to create a javascript that takes in Student information until the user either hits cancel or enters in blank text.
the information gets validated every time the user enters information if it is valid, it is then saved to a Student Object Array.
Here is my code:
var Student =[];
// Validates Student Courses, loops through making sure they are equal to courseList values.
function validateCourses(courses){
var valid='';
var courseList = ['APC100','IPC144','ULI101','IOS110','EAC150','IBC233','OOP244','DBS201','INT222'];
alert(courses);
for(var i =0;i<courseList.length;i++){
var a = courses;
a.splice();
if(a[i]!==courseList[i]){
valid=false;
}
else{
valid=true;
}
}
return valid;
}
function formatingName(name){
var res ='',cap='';
res = res + name.charAt(0).toUpperCase();
cap = res + name.substr(1);
return cap;
}
// I'm having issues with this validation for the student id. the student id can only be xxx.xxx.xxx
function validateStudentID(sid){
var validate=0;
var patt1 = /^\(?([0-9]{3})\)?([.]?)([0-9]{3})?([.]?)([0-9]{2})$/;
var result = patt1.test(sid);
return result;
}
var courseSelect=[];
var tag=0;
// this displays what users are in what course depending on what the user enters
function code(coursecode){
for(var w = 0;w<count;w++){
for(var t = 0;t<Student[w].courses.length;t++){
var a = Student[w].courses;
a.splice();
if(a[t] == coursecode){
tag=1;
}
}
if(tag){
courseSelect.push(Student[w].fname + " " + Student[w].lname + " " + Student[w].id + " " + Student[w].email);
}
}
alert('List students registered in ' + coursecode + ' :\n\n' + courseSelect.join('\n'));
}
// main functions and validation calls
var userInput = "";
var i=0,count=0,j=4,flag=false;
var result='',courses=[];
var Student,validCourses;
do{
userInput = prompt("Please enter first name, last name,student ID,\n" +
"email and courses (speareted by ',').");
if(userInput != null && userInput !=''){
result = userInput.split(',');
for(var i=4;i<result.length && i < 10;i++){
courses.push(result[i].toUpperCase());
}
// VALIDATION OF STUDENT ID AND STUDENT COURSES */
while(!flag){
var valid = validateStudentID(result[2]);
alert(valid);
if(valid){
id = result[2];
flag=true;
}
else {
alert(Student.id + " is not valid Student ID!" + "\n" + "Please try again.");
flag=false;
}
validCourse = validateCourses(courses);
if(validCourse){
flag=true;
}
else {
alert( validCourse + " is not the course provided by the CPD program! \n Please try again");
flag=false;
}
}
if(flag){
Student.push({
fname:formatingName(result[0]),
lname:formatingName(result[1]),
id:result[2],
email:result[3].toLowerCase(),
courses:courses,
});
count++;
i++;
}
else {
Student = [];
}
}
}while(userInput != null && userInput !='');
alert('There are total '+ count + ' students registered');
var coursecode = prompt("Please enter course code: ");
code(coursecode);
Some of the most obvious problems in your code are:
You have a while(!flag) loop after the input section. That loop contains no other request to input anything. Therefore it will run endlessly if your validate* methods return false.
Your regular expression /^\(?([0-9]{3})\)?([.]?)([0-9]{3})?([.]?)([0-9]{2})$/ isn't doing what you want it to do. You can simplify it to just /^[0-9]{3}\.[0-9]{3}\.[0-9]{3}$/ as all you want to know is whether your input parameter sid contains three number blocks, each of length 3. You don't need any braces for that and escaping them via \(? would anyways be wrong. You also didn't escape your points via \., which is wrong as they would match basically any character. You should read up more about regular expressions.
Your loop in validateCourses looks wrong. Why do you assign courses to a new variable (it isn't copied to a) and then call splice()? Your following if condition is also wrong, as it assumes that a and courseList have equal length and that the positions of the courses would match. That's certainly not what you want. You should check for each course in course whether it is contained in courseList, e.g.: var notInCourseList = courses.filter(function(course) { return (courseList.indexOf(course) == -1); }); and then return (notInCourseList.length == 0);. A forEach loop would be an easy alternative. You should read some tutorials about that.
Similarly, I don't see any good reason for var a = Student[w].courses; a.splice(); in code(). Just check directly on Student[w].courses.
Slightly more working jsfiddle here.

Repetition via for loop based on prompt output

So essentially what I'm trying to do is to figure out how to repeat a line x number of times based on a prompt's output.
i.e
<script>
var favnumber = Number(prompt("What is your favorite number?"))
for(var i=0;i<favnumber;i++){
System.out.println(name + "is bad at javascript");
}
</script>
any idea whats wrong?
JavaScript is not Java. So there is no function System.out.println() unless you define it.
To output you hav either to user the DOM, console or alert.
The later might look like this:
<script>
var favnumber = Number(prompt("What is your favorite number?"));
var name = 'Bob';
for(var i=0;i<favnumber;i++){
alert(name + " is bad at javascript");
}
</script>
Besides, try to get used to end every command with ;. Otherwise you run into many weird problems as a JavaScript beginner - and later as well.
JavaScript is not Java, so System.out.println doesn't have any special meaning. You have two options here: to use console.log(), or to use document.write().
I recommend you use console.log(), as it doesn't mess with the current page's HTML structure:
var favnumber = parseInt(prompt("What is your favorite number?"), 10);
var name = 'JavaScript';
for (var i = 0; i < favnumber; i++) {
console.log(name + ' is not Java');
}​
You'll need to open up your browser's JavaScript console to see those messages.
Using document.write() is a bit more cumbersome:
var favnumber = parseInt(prompt("What is your favorite number?"), 10);
var name = 'JavaScript';
for (var i = 0; i < favnumber; i++) {
document.write(name + ' is not Java');
document.write('<br />');
}​
Demo: http://jsfiddle.net/HC3Y2/

Categories

Resources