Trying to generate username Javascript - 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).

Related

Issue with passing property through function

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.

How do I get my function to add the userName to the h2 tag

I am new to javascript and I am having trouble getting the function below to work correctly. The function is supposed to add the userName plus what is already in the h2 header to the website after the user enters their name. It needs to show up as soon as the user enters their name.
/*
* this function will promtpt the user for their name;
* store name in a variable called userName.
* Use variable called phrase, which will hold h2 content
* Lastly write the "new" h2.
*/
function logIn() {
var userName = prompt("Please enter name");
pharse = document.getElementsByTagName('h2').innerHTML;
}
Alright, I'll take a crack at this
// This solution depends on you having an id on your 'h2' element
var userName = prompt('Please enter name');
var headerElem = document.getElementById('yourIdHere');
var pharse = headerElem.innerHTML;
headerElem.innerHTML = pharse + ' ' + userName;
Let me know if this is what you're looking for/if you want an explanation of why I did things the way I did!
Here's a working code pen you can play around with! http://codepen.io/csavage1994/pen/evvXoG
Here is an example of how to accomplish this:
https://jsfiddle.net/mcwc66op/
HTML
<h2>
H2 Text
</h2>
Javascript
var h = document.querySelector('h2');
var userName = prompt("Please enter name");
h.innerHTML = h.innerHTML + ' / ' + userName
document.getElementById("name").innerHTML += prompt("What is your name?");

How to put function using string control

On this first Image I would like to declare a variable that is string that would be used for making a condition if the username that is input if the string has 5 numbers it would be tag as EmployeeID if string has 10 numbers it would be tag as studentID.
So that before I create another app for User Interface for Employee and Student it would then evaluate.
I am not able deduce the code language, but I will write down a function considering that it's a jQuery.
var Id = "" , type = "";
if($("#Userid").val().length = 5)
{
Id = $("#Userid").val();
type = "employee";
}
elseif($("#Userid").val().length = 10)
{
Id = $("#Userid").val();
type = "student";
}
else
{
alert("Invalid ID");
}
Hope that's help! Now you can check type variable to decide the type of current logged in user.

Javascript prompt() alternative - Waiting for user response

I would like to ask series of questions to users in one function.
If I use prompt(), it is possible to ask all the questions in one function.
function question(){
var name = prompt("Enter your name");
var age = prompt("Enter your age");
}
But if I try to use input tag, this is impossible.
function question(){
document.write("Enter your name");
// you can't wait until the user responds. It will simply execute all the lines at once.
name = document.getElementById("input").value;
document.write("Enter your age");
age = document.getElementById("input").value;
}
If I do this, I can't use input tag to ask questions to users in one function. How can I wait until the user responds?
To chain prompts you can do something like:
const name = prompt("Enter your name");
if (!!name) {
const age = prompt("Enter your age");
if(!!age){
...
}
}
Or if you can use rxjs 5.5+ in your project you can use an observable to wait for the first prompt.
For example:
of(prompt("Enter your name"))
.pipe(first(), filter((name) => !!name))
.subscribe((name) => {
var age = prompt("Enter your age")
if(age) {
...
}
});
You can keep all your input boxes disabled except the first one. The second one can be enabled upon the user response to the first one. The line of inputs will go on like this.
Here is a little demonstration. Please note this is only a sample code which shows you the design pattern.
<input id="name"></input> <button onClick="getInput()">Ok</button>
<input id="address"></input> <button onClick="getInput()" disabled>Ok</button>
and in JS
var name, address;
functon getInput() {
name = document.getelementById("name").value;
address = document.getElementById("address").value;
if (address !== "")
document.getElementById("address").removeAttribute("disabled");
}
There are many advance methods than this is available in JS. But probably you should study this pattern first.
You cant take 2 different values from the same input in a function. You should create another input or some button to differentiate variables. For example:`
Enter your name
Enter your age
Save
var bSave = window.document.getElementById('bSave');
bSave.addEventListener("click", question);
var newName = window.document.getElementById('iName');
var newAge = window.document.getElementById('iAge');
function question() {
name=newName.value;
age=newAge.value;
}
</script>
`
document.write() is to writes HTML not for asking user input like prompt(). what you need is input validation before user submit the form like
function checkQuestion(){
if(document.getElementById("name").value == "")
alert('name empty');
if(document.getElementById("age").value == "");
alert('age empty');
}

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.

Categories

Resources