I have this javascript prompt, If it's not empty it connects to server, if it's empty, or user clicks cancel, I want to return to the start propmter again. I don't want the visitor to be able to join. What should I do?
var nick = prompt("Please enter your name", "")
if (nick != "");
{
$.connection.chathub.server.sendnick(nick);
}
else
{
// go back to start prompter again
}
use a while loop
http://www.w3schools.com/js/js_loop_while.asp
var nick ="";
while (nick == "");
{
nick = prompt("Please enter your name", "");
}
$.connection.chathub.server.sendnick(nick);
It seems that you need loop, loop does something while condition is true.
var nick = prompt("Please enter your name", "");
while (nick == "" || nick == null) {
nick = prompt("Please enter your name", "");
}
$.connection.chathub.server.sendnick(nick);
http://jsfiddle.net/48U79
Related
I am trying to make sure a user enters a value for the name and doesn't just leave it blank. I have a driver that calls the function and returns the name to a variable.
I've tried
if (name == null || name == "") {
getName();
}
both in the function and below the function call in the driver. I've also tried a while loop in both places. The If statement in the driver let me get by the prompt if I hit okay twice and even if I put a name in on the second time it wouldn't store it. The while loop wouldn't break even after I put a name in.
If this isn't enough code to tell just let me know.
function driver(){
var retName = getName();
}
function getName(){
var name = prompt("Enter your name");
return name;
I want the prompt to say please enter a valid name or at least just not let a user past until they enter something.
One option is to use do/while loop:
let name;
do {
name = prompt('Enter your name');
} while (!name);
console.log(name);
Just use a while loop:
var name = prompt("Enter your name:");
while (name == null && name == "") {
name = prompt("Enter your name:");
}
console.log("Valid name!");
console.log(name);
Note that the above does not deal with a whitespace-only name - so use trim too:
var name = prompt("Enter your name:");
while (name == null && name.trim() == "") {
name = prompt("Enter your name:");
}
console.log("Valid name!");
console.log(name);
Requirement : To validate password and emailID entered by user.
I have designed a dialog for user to enter there email id and password for creating their new account.
I want the the user input to be validated on the "next" button of the dialog.
I have written a JavaScript for it as shown below and added a custom action in "do action" of my dialog button.
function validatePassword(str szPasswordportal)
{
var newPassword = szPasswordportal;
var minNumberofChars = 6;
var maxNumberofChars = 20;
var regularExpression = /^[A-Za-z0-9`~!#%]{6,20}$/;
alert(newPassword);
if(newPassword = "") //if null
return false;
if(newPassword.length < minNumberofChars || newPassword.length > maxNumberofChars)
{
return false;
}
if(!regularExpression.password(newPassword))
{
alert("password should contain atleast one number ,one alphabet and one special character");
return false;
}
return true;
}
But this JS is not getting executed successfully.
Can someone help me out with this or with some other suggestion?
Your if condition have a syntax mistake.
if(newPassword = "")
= is assigning operator. If you want to check the value you have to use conditional operator == like below.
if(newPassword == "")
Also you have to add all the condition on else part, then only it will check the validation one by one, otherwise at the end it will automatically return the true value. Change your script like below.
function validatePassword(str szPasswordportal)
{
var newPassword = szPasswordportal;
var minNumberofChars = 6;
var maxNumberofChars = 20;
var regularExpression = /^[A-Za-z0-9`~!#%]{6,20}$/;
alert(newPassword);
if(newPassword == "" || newPassword.length < minNumberofChars || newPassword.length > maxNumberofChars)
{
return false;
} else if(!regularExpression.password(newPassword))
{
alert("password should contain atleast one number ,one alphabet and one special character");
return false;
} else {
return true;
}
}
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?");
}
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.
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.