Simple username prompt using JS not functioning correctly - javascript

I am making a very simple JavaScript username prompt, which, at the press of a button, requests that the user enters a username. After the user enters a name, the code writes a simple greeting with the user's username. However, if they leave it blank there is an alert which states the username cannot be blank.
The button works and the prompt comes up, but when you enter a blank username, the error doesn't come up.
I have tried to replace the null with undefined, but when I do that, any entry, including no entry of username, always brings up the error.
I cannot figure out what is wrong with my code below:
function usernametest() {
let username = prompt("Enter a username");
if (username != null) {
document.write("Hello " + username + "! How are you today?");
} else {
alert("Username cannot be blank!");
}
}
<input type="button" value="Click to test username prompt" onclick="usernametest();">

You should be checking against an empty string.
if (username != '')
If you want to make to make sure that the username is not only whitespace, you can use .trim(). See also my answer here.
if(username.trim())

Check against empty string too
if (username != null && username != '') {
document.write("Hello " + username + "! How are you today?");
}

function usernametest() {
let username = prompt("Enter a username");
if (username != '') {
document.getElementById('text').innerHTML ="Hello " + username + "! How are you today?";
}
else {
alert("Username cannot be blank!");
}
}
<input type="button" value="Click to test username prompt" onclick="usernametest();">
<div id='text'><div>

Related

i am trying to create a simple login page using javascript that will allow the user to input their username and password correctly until 3 tries ONLY

i am new to javascript and i was not able to figure out how to do it correctly. i was trying to create a simple page that will allow the user to input their username and password correctly but if they enter an invalid username or password 3 times, they won't be allowed to input again.
here is my code:
var UserInfo=[
{
username:"elliot",
password:"123"
},
{
username:"nicholas",
password:"456"
},
{
username:"rose",
password:"789"
},
{
username:"samantha",
password:"987"
},
{
username:"austin",
password:"654"
}
]
document.getElementById("btn").onclick=function(){
var username=document.getElementById("un").value
var password=document.getElementById("pw").value
for(i=0;i<4;i++){
if (username==UserInfo[i].username && password==UserInfo[i].password){
alert("Successfully logged in!");
}else{
alert("Please try again.");
}
}
}
You cannot use for loop for that. You need a counter to count how many attempts and increase that counter every time the user makes a mistake. Try something like this:
let attempts = 0
document.getElementById("btn").onclick=function(){
var username=document.getElementById("un").value
var password=document.getElementById("pw").value
if(attempts>=3){
alert("Sorry. Too many attempts.");
}
else{
if (UserInfo.find(el=> el.username === username && el.password === password)){
alert("Successfully logged in!");
}else{
attempts++
alert("Please try again.");
}
}
}

Unable to create proper authentication with prompt in javascript

I am creating authentication module with prompt in javascript.
Here is my code:
var pass1 = prompt('Please Enter Your Password',' ');
var originalPass = "mypassword";
if(pass1 == "mypassword"){
return;
}
else{
pass1 = prompt('Wrong Password. Please Enter Valid Password',' ');
}
HTML
<html>
<head></head>
<body>
<p>Hello, You are logged in </p>
</body>
</html>
In my code, if I enter the wrong password, the program control goes to else loop and display another prompt password field, when I enter the wrong password again at the second time, it loads the page and displays the HTML content.
What I want to do is, I don't want to get load the page until the user enters the right password.
If you get the correct password either use a innerHTML to write the content to your dom, or here I have used document.write.
To ask the password continuously from user, add a while loop and break it only if the condition is true.
var pass1 = prompt('Please Enter Your Password');
var originalPass = "mypassword";
while (1) {
if (pass1 == "mypassword") {
document.write("<html><head></head><body><p>Hello, You are logged in</p></body></html>");
break;
} else {
pass1 = prompt('Wrong Password. Please Enter Valid Password');
}
}

Attempt to display prompt until correct entry is entered in using Javascript

I'm trying to make "Enter your Password: " prompt appear until the correct password is entered. There is no limit to the attempts of password entry. So far I came up with this code using Javascript
function promptPassword() {
var name = prompt("Enter your Username: ");
var pwd = prompt("Enter your Password: ");
if (pwd == 'P#ssw0rd') {
alert("Password is correct, you are allowed to enter the site");
}
while (pwd != 'P#ssw0rd') {
alert("Login is incorrect");
prompt("Enter your Password: ");
}
}
<body onload="promptPassword();">
</body>
When I enter the correct password in first attempt the correct alert displays and it goes away when I click 'ok', which is expected.
When I type wrong passwords it keeps prompting to enter the password again, which is also as expected.
But the problem here is when I first enter wrong password and then enter right password in the next attempts, it still keeps prompting to enter the password again. Once the correct password is entered, "Password is correct, you are allowed to enter the site" alert should display and should go away, when 'ok' is clicked
Your prompt return value isn't being assigned in the while loop. Try this:
function promptPassword( )
{
var name = prompt ("Enter your Username: ");
var pwd = prompt ("Enter your Password: ");
while (pwd != 'P#ssw0rd'){
alert("Login is incorrect");
pwd = prompt ("Enter your Password: ");
}
alert("Password is correct, you are allowed to enter the site");
}
You need to set pwd to prompt("Enter your password: ");. If you don't, it will keep asking you, but the password variable will never update, and you'll be stuck in the loop forever!
function promptPassword( )
{
var name = prompt ("Enter your Username: ");
var pwd = prompt ("Enter your Password: ");
while (pwd != 'P#ssw0rd'){
alert("Login is incorrect");
pwd = prompt ("Enter your Password: ");
}
alert("Password is correct, you are allowed to enter the site");
}
promptPassword();
enter code here function promptPassword( )
{
var name = prompt ("Enter your Username: ");
var pwd = prompt ("Enter your Password: ");
while (pwd != 'P#ssw0rd'){
alert("Login is incorrect");
pwd = prompt ("Enter your Password: ");
}
alert("Password is correct, you are allowed to enter the site");
while ( name != "Youssef" ) { alert("Login is incorrect");
name = prompt ("Enter your Username: ");
} } promptPassword();

Javascript loops are crashing my website

So, I have a question about Javascript and HTML. Below I have my code, and I'm not sure why but whenever I try and run it(ie: hit Submit), my website freezes. I have it set right now so that it checks if the username/password EXISTS, but it does not have to be a combination of the 2 quite yet. Can someone help me?
<!DOCTYPE html>
<html>
<title> Welcome to my website!</title>
<body>
<form action="action_page.php" method = "post">
Username: <input type="text" name="user">
Password: <input type="password" name="pass">
<input type="submit" value="Submit" onclick="myLogin()">
</form>
<script type="text/javascript">
function myLogin(){
var usernames = ["rdoucett", "hovland"];
var passwords = ["Rd200161", "hovland1"];
usernames[5] = "stop";
passwords[5] = "stop";
var a = false;
var b = false;
var i = 1;
while(a===false) {
if(usernames[i] != form.user.value) {
i++;
}else if(usernames[i] == form.user.value){
a=true;
}else if(usernames[i] == "stop"){
alert("Incorrect username or password!");
a=true;
};
};
i = 1;
while(b===false) {
if(passwords[i] != form.pass.value) {
i++;
}else if(passwords[i] == form.pass.value){
b=true;
}else if(passwords[i] == "stop"){
alert("Incorrect username or password!");
b=true;
};
};
if(b&&a===true){
alert("Welcome " + document.getElementsByName("user") + "!");
}else{
alert("I do not recognize you " + document.getElementsByName("pass") + "!");
};
};
</script>
</body>
Don't use a while loop at all, just exit the myLogin function if it was an invalid username or password.
Be aware that what you have written here is completely insecure. Anyone visiting your website with even a basic technical knowledge can see your full list of usernames and passwords.
I changed your code a lot, but I think it is what you wanted. In your scenario beside a few errors, any valid username and any valid password would match. (i.e. user = "rdoucett" and psw= "hovland1").
function myLogin(){
var usernames = ["rdoucett", "hovland"];
var passwords = ["Rd200161", "hovland1"];
var username;
for (var i = 0; i < usernames.length; i++) {
if (usernames[i] == form.user.value) {
username = usernames[i];
break;
}
}
if (!username || passwords[i] != form.pass.value) {
alert("Incorrect username or password!");
}
else {
alert("Welcome " + document.getElementsByName("user") + "!");
}
};
From the security point of view, as already been said this is very insecure. You should think the HTML and JS as information any client can see. So this kind of functionality is what you must do server side.
Also note that the alerts wont avoid the form of being submitted. If you want to avoid that, you should add return false;.

Obtaining output of php file with Javascript

I have a php file stored remotely. It uses post to take 2 variables, "username" and "password", which will then echo either Valid or Invalid depending on it's existence in my database. I currently use this with my android application to log users in.
I would like to use this same script for logging into my website that I am building. I need to be able to pass 2 variables that I have obtained from an HTML form to a javascript function which will take the variables, run them though the php query, read the echoed output and decide to return true or false to the form. Below is the code I currently have for the script
Javascript code:
<script type="text/javascript">
function Login(){
var username = document.getElementById('username').value;
var password = document.getElementById('password').value;
if (username == "" || password == "") {
alert ("Please fill in username and password fields");
return false;
}
$.post("my_query_url.php",{username:username, password:password}, function(data) {
if (data.toLowerCase == "valid")
return true;
else
return false;
});
}
</script>
HTML form:
<form action="Main.html" method="post" onsubmit=" return Login();">
Username: <br>
<input type="text" name="username" id="username"><br>
Password: <br>
<input type="password" name="password" id="password"><br><br>
<input type="submit" value="Login">
</form>
Currently, it always sends the user to my Main.html page with any non-empty username/password input.
I'm not very well versed in these two languages, but I need to learn quickly as they are important for my Senior Project class semester, and especially these next two weeks. Is this possible to do with Javascript and HTML only? Some pointers will be much appreciated! Thank you!
You actually are almost all the way there. You just need to return false from your Login function to prevent the default action of the form from triggering (which is to redirect to main.html). Then, instead of relying on the form to redirect the user, you will need to do so yourself via javascript.
<script type="text/javascript">
function Login(){
var username = document.getElementById('username').value;
var password = document.getElementById('password').value;
if (username == "" || password == "") {
alert ("Please fill in username and password fields");
return false;
}
$.post("my_query_url.php",{username:username, password:password}, function(data) {
if (data.toLowerCase() === "valid")
window.location.href = "./Main.html"; //redirect the user
else
return false;
});
return false
}
</script>

Categories

Resources