Code won't run due to string length issue - javascript

Got a simple Javascript program here to accept and check a password. It should:
Ask you to enter a new password
Check the strength of the password which outputs a message of either weak or strong based on a length of <6 or >6.
Get you to re enter this password to enter the 'system'
Give you simple prompts or 2 random letters if the password is not correct.
Everything works except the strong/weak checker. It has a problem getting the length of passwordEntry since it apparently doesn't exist as an entity.
Any ideas would be much appreciated
var pass;
var main = function(){
strengthCheck((prompt("Please Choose a New Password to Begin"));
}
var strengthCheck = new function(passwordEntry){
score = 0;
// adds to the score variable depending on the length of the password
if(passwordEntry.length > 6{
score=(score+1);
}
//reads messages back stating how strong password is based on length
if(score=0){
console.log("Your Password is Weak");
}
else if(score=1){
console.log("Your Password is Strong");
}
var passContinue = prompt("Do you want to continue with this password? Yes or no?")
if(passContinue === "no" || passContinue === "No"{
main();
}
else{
pass = passwordEntry;
console.log("Your new password has been changed to " + pass);
passwordChecker(prompt("Thank You. Please Enter Your Password Below"));
}
}
var passwordChecker = function (attempt){
if(attempt == pass){
console.log("Correct password. The system has logged you on");
}
else{
//if the password is wrong, runs the incorrectpassword() function
console.log("Incorrect Password");
IncorrectPass();
}
}
}
var IncorrectPass = function (){
var clueanswer = prompt("Do You Want A Clue");
if(clueanswer === "Yes" ||clueanswer === "yes"){
console.log("I will give you two random letters");
// takes two random locations from the string array and reads them back
var randarray1 = Math.floor((Math.random()*7)+1);
var randarray2 = Math.floor((Math.random()*7)+1);
var randletter1 = pass[randarray1];
var randletter2 = pass[randarray2];
console.log(randletter1+" "+randletter2);
passwordChecker("Please try entering your password again");
}
else{
console.log("GoodBye");
}
}
main()

This part looks very wrong:
if(score=0){
console.log("Your Password is Weak");
}
else if(score=1){
console.log("Your Password is Strong");
}
You should use == or === instead of = which is used for assignment rather than comparison.
This doesn't make sense either:
var main = function(){
strengthCheck((prompt("Please Choose a New Password to Begin"));
}
There are three opening parentheses and only two closing ones. Smells like parser error.

Change this...
var strengthCheck = new function(passwordEntry){
to this...
var strengthCheck = function(passwordEntry){
When you use new, you're not using it to create a new function. You're using it to call the function as a constructor, which will return an object. (An empty object in your case.)
Also, you have many syntax errors in your code. Use a code validator like http://jshint.com as well as a beautifier like http://jsbeautifier.org to clean up your code.

Related

If/Else statement nested in While loop

(I am very new to JavaScript and am writing this to try and get used to using it a bit more - which is why I'm using an object to store usernames and passwords. I'm learning this as part of an apprenticeship but this is during my own time to further my knowledge on JS)
I have tried writing a small piece of code that should ask the user to enter a username, which will be cross-checked against the property names in the object "userNames". The user is then asked to enter a password for this user which is then checked against the password set as the value of the corresponding property with the right username.
I feel as though part of the problem is to do with me trying to use the variable "enteredPassword" (set to the user's input for the password as a method) of "userNames".
If the username or password are incorrect after 3 attempts then I'd like the window to close.
my text editor is saying that the If statement is missing a branch and I'm not sure if this is affecting whether this works or not.
var userNames = {Tom:"PassW0rd", Bill:"Apples40C0lander", Ryan:"M1911p4ck4ge"};
var Greeting = "Insert Username:";
var i = 0;
while (i < 3)
{
var enteredUserName = prompt(Greeting);
var enteredPassword = prompt("enter password for " + enteredUserName);
if ((userNames.hasOwnProperty(enteredUserName)) && (userNames.enteredUserName==enteredPassword)) {
alert("Welcome");
break;
} else {
alert("incorrect Username or Password");
alert("");
window.open('', '_self', ''); window.close();
window.open('', '_self', ''); window.close();
i++
}}
A simple change is enough here :
userNames[enteredUserName].
In JavaScript, Object can also accessed like array.
If you use userNames.enteredUserName , then it will check {enteredUserName:somevalue} (ie, enteredUserName will be considered as a String. but if you use it as userNames[enteredUserName] , then enteredUserName will be considered as variable and index to the Object.
Try below snippet.
var userNames = {Tom:"PassW0rd", Bill:"Apples40C0lander", Ryan:"M1911p4ck4ge"};
var Greeting = "Insert Username:";
var i = 0;
while (i < 3)
{
var enteredUserName = prompt(Greeting);
var enteredPassword = prompt("enter password for " + enteredUserName);
if ((userNames.hasOwnProperty(enteredUserName)) && (userNames[enteredUserName]==enteredPassword)) {
alert("Welcome");
break;
} else {
alert("incorrect Username or Password");
alert("");
window.open('', '_self', ''); window.close();
window.open('', '_self', ''); window.close();
i++
}}

Why doesn't this if/else run before the other prompts

var password = prompt('Please enter your password.');
if (password!=="cat" && password!=="cow") {
console.log(password);
location.assign("http://www.google.com")
}
//The rest of prompts
var age = prompt("What is your age?");
var name = prompt('What is your name?');
var homeTown = prompt('Where are you from?');
var favoritDog = prompt("What's your favorite dog?");
So that's my code, (I'm a beginner and just messing around with concepts), if the incorrect password is put in, shouldn't it redirect me to google right away? Because when I run that code, it gives me all the prompts first before the redirect. Any help is appreciated, thank you.
Because doing location.assign will not stop the execution of JavaScript, it will keep going. It will do the location assignment after the sequential JavaScript finishes. Since prompt blocks the current execution, for it to finish it will need to go through the prompts. To prevent it simply add your prompts to an else:
var password = prompt('Please enter your password.');
if (password!=="cat" && password!=="cow") {
console.log(password);
location.assign("http://www.google.com")
} else {
//The rest of prompts
var age = prompt("What is your age?");
var name = prompt('What is your name?');
var homeTown = prompt('Where are you from?');
var favoritDog = prompt("What's your favorite dog?");
}

Javascript Functions with loops assignment

I found a similar question for this same assignment but that person was using a different type of loops. I have been struggling with this assignment and even with the teacher giving me pseudo code to try to explain it further I am still having difficulties with it writing out what it's supposed to in the end.
We are supposed to create an array that holds the price of theater tickets, then make a html table that has the different level of tickets and prices that correspond with the numbers in the array. After this we prompt the user for their name and validate that they did enter something. Then we are supposed to create a function named numSeats that prompts the user for the number of
seats that they want to buy and validate that they entered a number and the maximum number of seats they can buy in one transaction is 6.
We are supposed to use a loop to
prompt the user until they enter a valid number, then create a function named seatingChoice that prompts the user for where they would like the seats to be by indicating the correct number from the table.
seartingChoice also needs to validate that they entered a number 1-4 and use a loop to prompt the user until they enter a valid number. If the user at any time hits the cancel button in a prompt we are supposed to give an alert of "Sorry you changed your mind". This is missing from my code because i haven't figured out how to do that.
When the program calculates everything and writes to the screen in the end it is supposed to write like "UsersName ordered #tickets for a total of dollaramt" but instead it writes "Null ordered null tickets for a total of $null." The following is what i have the the javascript part of the code:
var Prices = [60, 50, 40, 30];
var Usersname = prompt("Please enter your name");
while(Usersname = null)
{
Usersname = prompt("Please enter your name");
}
function numSeats () {
var seats = prompt("Please enter the number of seats you want to buy");
parseInt(seats);
while((seats = null)||(seats > 6))
{
seats = prompt("Please enter a number between 1 and 6");
parseInt(seats);
}
return seats;
}
var seatswanted = numSeats ();
function seatingChoice () {
var choice = prompt("Please enter where you would like your seats to be located by indicating the correct number from the table");
parseInt(choice)
while((choice = null)||(choice > 4))
{
choice = prompt("Please enter a number between 1 and 4, corresponding to your section choice");
parseInt(choice);
}
return choice;
}
var seating = seatingChoice();
var dollaramt = (seatswanted * Prices[seating-1]);
document.write(Usersname + " ordered " + seatswanted + "tickets for a total of " + "$" + dollaramt + ".");
Instead of comparison operator you are using assignment operator:
var Usersname = prompt("Please enter your name");
while(Usersname = null)
{
Usersname = prompt("Please enter your name");
}
and prompt return empty string if user wont input anything so instead of null compare it to empty string i.e, ''. so change this to:
var userName = prompt("Please enter your name");
while(userName == '')
{
userName = prompt("Please enter your name");
}
There are several errors in your code. You can try your code using jsfiddle (you can try your code properly modified here: http://jsfiddle.net/pu3s0n50/).
Your errors are that you assign Username, seats and choice instead of comparing them, i.e.:
while(Usersname = null)
should be
while(Usersname == null)
and
while((seats = null)||(seats > 6))
should be
while((seats == null)||(seats > 6))
and finally
while((choice = null)||(choice > 4))
should be
while((choice == null)||(choice > 4))
The error I do not know why this happening, but this maybe solve your issue.
var Usersname = '';
Usersname = prompt('Choose a Username:');
this works. And you need the same for the others prompt.
Also if you want seat in rang 1-6: while((seats = null)||(seats > 6)) its wrong. Change to ((seats <= 6) && (seats > 0))
Maybe this could help you.
Best regards.

javascript: counting digits in a text input

I have a piece of HTML that creates a web form with three text fields (name, group and number), all of which are validated using JavaScript to check that there is data inputted into them. In the last text field, I need to introduce an additional bit of JavaScript to check that the data inputted by the user is also four digits long (for example 2947 or 94Q3). As a complete JavaScript novice, I'm not sure how I would do this! Would I have to create a variable that could take the value of the inputted data, then count the digits of the variable, or could I do it directly from the field? Here is the Javascript section of my code:
function validateForm() {
var result = true;
var msg = ””;
if (document.Entry.name.value == ””) {
msg += ”You must enter your name\n”;
document.Entry.name.focus();
document.getElementById(‘name’).style.color = ”red”;
result = false;
if (document.Entry.group.value == ””) {
msg += ”You must enter the group\n”;
document.Entry.group.focus();
document.getElementById(‘group’).style.color = ”red”;
result = false;
}
if (document.Entry.number.value == ””) {
msg += ”You must enter the number\n”;
document.Entry.number.focus();
document.getElementById(‘number’).style.color = ”red”;
result = false;
}
if (msg == ””) {
return result;
} {
alert(msg)
return result;
}
}
If possible, could you tell me what code I would need to insert? Thank you!
Place this block in your conditions list:
if (document.Entry.number.length!=4) {
msg+=”You must enter 4 digits \n”;
document.Entry.number.focus();
document.getElementById(‘number’).style.color=”red”;
result = false;
}
if (document.Entry.number.value==””) {
msg+=”You must enter the number \n”;
document.Entry.number.focus();
document.getElementById(‘number’).style.color=”red”;
result = false;
}
change this to
if (document.Entry.number.length != 4){
msg+="Number must be exactly 4 characters \n";
document.Entry.number.focus();
document.getElementById('number').style.color="red";
result = false;
}

Javascript: registration form help required

I'm a rookie scripter and what I'm trying to do is: create a registration form and a calculator. If you enter a password less than 5 symbols or a username less than 3 symbols you will not be able to continue. But even if I enter an username with more than 3 symbols and a password with more than 5 symbols it still displays the error message.
The code: http://pastebin.com/KqYbDJMw
var user = document.forms[0].username.value;
var pw = document.forms[0].password.value;
function triggerCalc(){
if (pw.length < 5 && user.length < 3){
alert("An error occured");
}
else {
alert("Thank you for registering to my website.");
var action = prompt("Welcome to my calculator. For addition press 1, for substraction press 2, for multiplication press 3, for division press 4 and for square root press 5:", "");
var firstNum = new Array();
var secondNum = new Array();
var result = new Array();
You want to fail if either of those conditions are true, so use || (or) instead of && (and)
if (pw.length < 5 && user.length < 3)
should be
if (pw.length < 5 || user.length < 3)
Also, you want to fetch the current values each time you do your check, so this
var user = document.forms[0].username.value;
var pw = document.forms[0].password.value;
should be inside your function. Ie
function triggerCalc(){
var user = document.forms[0].username.value;
var pw = document.forms[0].password.value;
The problem is you get :
var user = document.forms[0].username.value;
var pw = document.forms[0].password.value;
function triggerCalc(){...
on load. So it will always be blank. To get it at the time the user clicks 'continue..' move it inside the function like so:
function triggerCalc(){
var user = document.forms[0].username.value;
var pw = document.forms[0].password.value;
...
You are not too far off. The two main changes are you need to put your variable assignment inside of the function you are calling so it can get the values when the submit button is pressed.
Also you probably want to use an Or instead when validating the fields. Here is an example:
function triggerCalc(){
var user = document.forms[0].username.value;
var pw = document.forms[0].password.value;
if (pw.length < 5 || user.length < 3){
alert("An error occured");
}
If you're doing any kind of validation, there are some great jQuery libraries that make it look great and are easy to implement. You might want to to a quick google search.

Categories