Why does this think it's correct? - javascript

I'm new to js and I have this very simple code. It's supposed to be a login, and it's not working. I don't need any tips on making it better, I'm planning to do that when this starts to work.
<!DOCTYPE html>
<head> Sign-in </head>
<body>
<script type="text/javascript">
var em = prompt("Enter E-mail Here:")
if(em = "I hid this to prevent spam"){
var pa = prompt("Enter Password Here:")
if(pa = "jct28if5"){
alert("Welcome!")
}
else{
alert("Incorrect password!")
}
}
else {
alert("Invalid e-mail!")
}
</script>
</body>
</html>
What it's doing now is no matter what, it thinks that the correct e-mail and password were used. Could somebody help?

I've fixed your code up a bit. Some things to note.
You can't just put raw content in the <head>.
Your password is in the raw source of the page, so anyone can view the page source and see what the correct password is. That's an absolutely horrible design. Passwords should be passed to server side where they're checked for validity.
In C like programming language such as Javascript, == tests for equality and will return a boolean. The = sign assigns a value to a variable.
<!DOCTYPE html>
<head>
<title>Sign-in
</title>
<script type="text/javascript">
var em = prompt("Enter E-mail Here:")
if(em == "I hid this to prevent spam"){
var pa = prompt("Enter Password Here:")
if(pa == "jct28if5"){
alert("Welcome!")
}
else{
alert("Incorrect password!")
}
}
else {
alert("Invalid e-mail!")
}
</script>
</head>
<body>
</body>
</html>

Just one addition:
== checks value
=== checks value and type
Someone who deactivates js or doesn't support it like curl/wget and others, will not be stopped by this, except you load the whole website with js, what might be stupid cause of search engines might not index the content though.
Hope this helps.

fixed
var em = prompt("Enter E-mail Here:")
if(em === "I hid this to prevent spam"){
var pa = prompt("Enter Password Here:")
if(pa === "jct28if5"){
alert("Welcome!")
}
else{
alert("Incorrect password!")
}
}
else {
alert("Invalid e-mail!")
}
You use a single = when you're assigning a variable a value. like var x = 1.
But if you want to check equality, use ===. like if(x ===1)

Related

Need help replicating a little bit of JavaScript

I am working on some basic JavaScript.
I have a muse website and I'm using this script so users can enter a specific password and be redirected to a page, I need to be able to change this so I can do this multiple times, so: multiple passwords going multiple places.
For example, when users click a button they are asked for a password, when they enter CUSTOMPASSWORD1 they will be redirected to mywebsite.com/custompassword1.html how would I edit this script so that they could also type in CUSTOMPASSWORD2 and be redirected to mywebsite.com/custompassword2.html?
Script below:
<SCRIPT>
function passWord() {
var testV = 1;
var pass1 = prompt('Enter Store Code Here',' ');
while (testV < 3) {
if (!pass1)
history.go(-1);
if (pass1.toLowerCase() == "CUSTOMPASSWORD1234") {
alert('You are being redirected!');
window.open('CUSTOMPASSWORD1234.html');
break;
}
testV+=1;
var pass1 =
prompt('Access Denied - Store Code Not Recognised, Please Try Again.','Password');
}
if (pass1.toLowerCase()!="password" & testV ==3)
history.go(-1);
return " ";
}
</SCRIPT>
<CENTER>
<FORM>
<input type="button" value="Enter Store Code" onClick="passWord()">
</FORM>
</CENTER>
I believe what you are trying to do is simply redirect the user to whichever url they enter in the prompt.
To achieve that, we can use a similar approach:
function redirect() {
var pass1 = prompt('Enter Store Code Here', ' ');
if (!pass1) {
history.go(-1);
} else {
alert('You are being redirected!');
window.open(pass1 + '.html');
}
}
<center>
<form>
<input type="button" value="Enter Store Code" onClick="redirect()">
</form>
</center>
I'm not sure I entirely understand the question, I think you could just do this:
<SCRIPT>
function passWord() {
var testV = 1;
var pass1 = prompt('Enter Store Code Here',' ');
while (testV < 3) {
if (!pass1)
history.go(-1);
if (pass1.toUpperCase() == "CUSTOMPASSWORD1234") {
alert('You are being redirected!');
window.open('CUSTOMPASSWORD1234.html');
break;
}
else if (pass1.toUpperCase() == "CUSTOMPASSWORD2"){
window.open('CUSTOMPASSWORD2.html');
break;
}
testV+=1;
var pass1 =
prompt('Access Denied - Store Code Not Recognised, Please Try Again.','Password');
}
if (pass1.toLowerCase()!="password" & testV ==3)
history.go(-1);
return " ";
}
</SCRIPT>
<CENTER>
<FORM>
<input type="button" value="Enter Store Code" onClick="passWord()">
</FORM>
</CENTER>
You also have what I assume is an error with
(pass1.toLowerCase() == "CUSTOMPASSWORD1234")
since this will never evaluate to true since CUSTOMPASSWORD1234 is upper case. Also you don't have an evaluation for CUSTOMPASSWORD1.
It seems like you're lacking in basic JS and programming knowledge so I'd recommend reading some basic tutorial in programming concepts before you start building stuff. Just hacking together tutorials will make spaghetti code and you won't learn.
Trent's answer is better design which you should use, this answer is just how to specifically implement what you are asking for.

JavaScript prompt window disappears when navigating to other tab

I have written following snippet to enable password on my site, but if I navigate to different tab on the browser, the password prompt disappears and this feature is not useful anymore.
function passWord(title) {
var pwd = prompt(title);
switch (pwd) {
case '2017': true;
break;
case null: passWord('Access Denied - Password Incorrect, Please Try Again.');
break;
default: passWord('Access Denied - Password Incorrect, Please Try Again.');
}
}
I am calling this function in body tag.
<body onload="passWord('Please enter password here')">
You can try this method:
<style>#screen {display: none;}</style>
<body onload="passWord();">
<div id="welcome">
<h1>Welcome Page</h1>
</div>
<div id="screen">
<h1>Unique Page</h1>
</div>
<script>
function passWord() {
var welcome = document.getElementById("welcome");
var screen = document.getElementById("screen");
var pwd = prompt("Enter your password", "TYPE HERE");
switch(pwd) {
case "2017":
screen.style.display = "block";
welcome.style.display = "none";
break;
default:
screen.style.display = "none";
welcome.style.display = "block";
}
}
</script>
</body>
As #Caleb Black comment - It's better using php for this things if security matter. Good Luck!
You can use the focus event to see when the users comes back to your page:
var didEnterPassword = false;
window.addEventListener("focus", function(e){
if(!didEnterPassword && prompt("hello again") == "my secret password"){
didEnterPassword = true;
}
})
Keep in mind though that this is incredibly insecure since anyone can get my secret password when they start digging in your code.
You can use a while loop which keeps running as long as the user hasn't sent their answer:
var pwd;
while(pwd == null) pwd = prompt(title);
Note that it will not preserve any text entered before the focus was lost.

How to display the user's data with calculations

I'm very new to HTML and especially JavaScript and I already have troubles.
How could I display all the data I took from the user taken through promt.
nothing seems to work from what I know.
here is the code.
function myFunction() {
var userinput;
var userName = prompt("Please enter your name to proceed");
if (userName == true)
{
document.write ("Welcome to Office Cheapo, "+ userName + ". Here is your invoice:");
}
var notebook = prompt("How many notebooks do you want to buy?" , "1 to 10");
if (notebook == true){
document.write ("Notebooks bought -- "+ notebook);
}
var pens = prompt("How many pens do you want to buy?", "1 to 10");
if (pens == true){
document.write ("Pens bought -- "+ pens);
}
var usb = prompt("How many USB Flash Drives do you want to buy?", "1 to 10");
if (usb == true){
var taxusb = (usb*6.75)*0.05;
}
document.write ("USBs bought -- "+ usb);
}
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Cheapo Order</title>
</head>
<body>
<div>
<button onclick="myFunction()">Make an order</button>
</div>
</body>
</html>
userName will either be a string or null (if the user canceled the prompt). So username == true will always be false and your document.write will never be executed.
What you might want is:
if (userName) {
This will execute your block provided that userName is not a falsy value.
The following are all falsy values:
null
undefined
0
""
false
NaN
So as long as the user enters something and presses OK in your prompt, the condition will be met and your code within the if branch, executed.

Javascript OnClick Function not Working (with partial code in head)

I was renovating my website while I came across this error.
It is a simple username-password Javascript calling function.
Here is the code (because of confidentiality I would not like to give out any usernames, passwords, links, or function names):
<head>
<script>
function ----() {
var username = prompt("Please enter your username.");
if (username.toLowerCase() == "-----"){
var password = prompt("Please enter your password.");
if (password.toLowerCase() == "-----"){
window.open('http://example.com',"_self")
}
else{
alert('Incorrect password. Please try again.')
}
}
else{
alert('Incorrect username. Please try again.')
}
}
</script>
</head>
<body>
<p><a onclick="----()" href="javascript:void(0);">------</a></p>
</body>
Please don't criticize my code; I've only been coding for 1~2 years. I would love to learn more from this renovating experience!
Thanks!
Jefferson Yu
You have redundant else statements. I have added a sample function called foo to explain. Try to adapt indentation in your code, that will save you from creating syntactical errors.
<html>
<head>
<script>
function foo() {
var username = prompt("Please enter your username.");
if (username.toLowerCase() == "user"){
var password = prompt("Please enter your password.");
if (password.toLowerCase() == "pass"){
window.open('http://example.com',"_self");
}
}
else{
alert('Incorrect password. Please try again.');
}
}
</script>
</head>
<body>
<p><a onclick="foo()" href="javascript:void(0);">click me</a></p>
</body>enter code here
</html>

JQuery random number guessing game: loop woes

I am trying to make a simple number guessing game: a random number between 1 and 9999999999 is generated and printed to the console. I want the user to input their guess in a form - and keep looping guesses until the guess matches the random number.
Here is my html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Random Number Guess</title>
</head>
<body>
<!--text display/button -->
<p>Try and "guess" the random number! Click "Generate new random number" to start"</p>
<div id="out1"></div>
<form id="promptUser">
Your guess:
<input type="text" id="inUserGuess">
<input type="submit" value="Submit">
</form>
<br>
<button id="btn1">Generate new random number</button>
<div id="in1"></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>/*SEE SCRIPT BEOW */</script>
</body>
</html>
And here is the javascript/jquery inside:
$(document).ready(function() {
/*initialize random number*/
var randNum = Math.round(Math.exp(Math.random()*Math.log(10000000-0+1)));
console.log(randNum);
var win = false;
while (win = false) {
$('#promptUser').on('submit', function(e){
e.preventDefault;
var userGuess = $('#inUserGuess').val();
console.log("User guess:" + userGuess);
});
/*yes: "congrats! start again"*/
if (userGuess == randNum){
console.log("User guess is correct");
alert("You got it! Try another round.");
win = true;
}
/*no: "not quite. guess again."*/
else {
console.log("user guess is incorrect");
alert("Not quite. Guess again.");
win = false;
}
}
In order to keep the user guessing until they get it right, I put the guess input inside a while loop and used and if/else statement to determine whether their guess matches the random number.
It seems as though the code gets messed up somewhere before the if/else statement- the console log never shows up. Instead, a new random number is generated when submit is pressed.
I know the syntax of gathering input works - before I attempted to give the user infinite guesses the if statement ran fine (though a new random number was automatically generated after each "play", regardless of correct/incorrect guess)
I feel stupid asking this - but I've been fiddling with it for hours.
[[EDIT]] I now have the submit button event handler doing two things: storing the user input to userGuess and checking to see whether or not it matches randNum, but still is stuck in an infinite loop:
<script>
/*initialize random number*/
var randNum = Math.round(Math.exp(Math.random()*Math.log(10000000-0+1)));
console.log(randNum);
var userGuess = "";
do {
$(document).ready(function() {
$('#promptUser').on('submit', function(e){
e.preventDefault;
userGuess = $('#inUserGuess').val();
console.log("User guess:" + userGuess);
if(userGuess == randNum){
console.log("user guess is correct");
alert("That's right! Play again.");
}
else{
console.log("user guess is incorrect");
alert("Not quite. Guess again.");
}
});
});
}
while (userGuess != randNum);
/*generate new random number each on button click */
$('#btn1').on('click', function(){
var randNum = Math.round(Math.exp(Math.random()*Math.log(10000000-0+1)));
console.log(randNum); /*(return random number to console for cheating)*/
});
</script>

Categories

Resources