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

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>

Related

I am creating a login system in HTML...I have Used written a piece of code but It dosn't seem to workup..requesting to please answer

This is the code I had written
but the If...Else statement doesn't seem to work
(I have used MAPS here because I feel it easier{Please suggest if there's anything else that can be used to make it easier!})
I have attached my code for reference...
awaiting response
thanks in advance!!
<script>
function submit(){
alert("hello");
var username=document.getElementById("username");
var password=document.getElementById("password");
var map = new Map();
map.set("Doctor_1","Doctor_Password.1");
map.set("Doctor_2","Doctor_Password.2");
map.set("Doctor_3","Doctor_Password.3");
map.set("Nurse_1","Nurse_Password.1");
map.set("Nurse_2","Nurse_Password.2");
map.set("Teaching_1","Teaching_Password.1");
map.set("Teaching_2","Teaching_Password.2");
map.set("Teaching_3","Teaching_Password.3");
map.set("Student_1","Student_Password.1");
map.set("Student_2","Student_Password.2");
map.set("Student_3","Student_Password.3");
map.set("Student_4","Student_Password.4");
if username in map {
if password in map {
alert("password found");
}
else{
alert("Wrong PASSWORD...");
}
}
else{
alert("Wrong USERNAME...");
}
</script>
You are mapping usernames to passwords. You should try something like this.
First, check if the map has username. If it does, then retrieve the password for that username using map.get(username) and compare it with the user-input. If it matches, you are good to go.
function submit(){
var username = document.getElementById("U").value;
var password = document.getElementById("P").value;
var map = new Map();
map.set("Doctor_1","Doctor_Password.1");
map.set("Doctor_2","Doctor_Password.2");
map.set("Doctor_3","Doctor_Password.3");
map.set("Nurse_1","Nurse_Password.1");
map.set("alexa", "12345");
map.set("Nurse_2","Nurse_Password.2");
map.set("Teaching_1","Teaching_Password.1");
map.set("Teaching_2","Teaching_Password.2");
map.set("Teaching_3","Teaching_Password.3");
map.set("Student_1","Student_Password.1");
map.set("Student_2","Student_Password.2");
map.set("Student_3","Student_Password.3");
map.set("Student_4","Student_Password.4");
if (map.has(username)) {
if (map.get(username) === password) {
alert("Welcome!");
} else {
alert("Wrong password!");
}
} else {
alert("Sorry!");
}
}
<input type="text" placeholder="Username" id="U">
<input type="text" placeholder="Password" id="P">
<button onclick="submit()">Submit</button>
Here’s my modified version. Your description of what “doesn’t seem to work” is not very specific, but I did notice you were missing a final brace.
If that wasn’t your issue, you can review my comments below. Note that in your code username and password are elements and not strings, so you’ll need to extract string values from them.
function submit() {
alert("hello")
/*
username and password are DOM elements
*/
var username = document.getElementById("username")
var password = document.getElementById("password")
var accounts = {
Doctor_1: 'Doctor_Password.1',
Nurse_1: 'Nurse_Password.1'
//etc
}
if username in accounts {
if password in Object.values(accounts) {
// it is strange to check against everyone's passwords though
alert("password found")
}
else if (accounts[username] == password) {
// I added this option
alert('username and password match!')
}
else {
alert("Wrong PASSWORD...")
}
}
else {
alert("Wrong USERNAME...")
}
} //this last brace was missing

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.

Password protected download link

I want to make a simple password protected link that enables users (with the correct password) to download a zip file. The link, as in the code below, is "folder/history.zip". The link is a simple text ("Open"), not a button. I don't have any experience with javascript. The problem is that the password protection does not work when I tried. I just want to know how can I edit the code below to make it work?.. I don't have any experience with javascript so I appreciate any help!
html:
open
Javascript:
<SCRIPT type="text/javascript">
function passWord() {
var testV = 1;
var pass1 = prompt('Please Enter Your Password',' ');
while (testV < 3) {
if (!pass1)
history.go(-1);
if (pass1.toLowerCase() == "teacher") {
alert('You Got it Right!');
window.open('folder/history.zip');
break;
}
testV+=1;
var pass1 = prompt('Access Denied - Password Incorrect, Please Try Again.','Password');
}
if (pass1.toLowerCase()!="password" & testV ==3)
history.go(-1);
return " ";
}
</SCRIPT>
<CENTER>
<FORM>
<input type="text" value="Enter Protected Area" onClick="passWord()">
</FORM>
</CENTER>
try the below code,
JS:
function passwd(){
var password = prompt('Enter the password to download the file:');
if(password.toLowerCase() == "teacher"){
window.open("folder/history.zip")
}else{
alert("incorrect password!! please try again");
}
}
HTML
<input type="button" value="download zip file" onClick="passwd()"/>

Javascript help needed for simple form validation

I am currently trying to create a very simple validation script with JS. Basically, I want a alert to come up if the text inputted into a form is shorter than 5 characters, or longer than 25.
<!doctype html>
<html>
<head>
<title>Password Validator</title>
</head>
<body>
<script>
function validate()
{
var yourpw = document.forms.passwordform.yourpassword.length;
if (yourpw < 5);
{
alert("password is too short");
return false;
}
if (yourpw > 25)
{
alert("your password is too long")
return false;
}
}
</script>
<h1>Password Validator</h1>
<p>Please create a new password below</p>
<p>Be sure you password follows these guidelines</p>
<ul>
<li>No shorter than 5 characters</li>
<li>No longer than 25 characters</li>
</ul>
<br>
<form name="passwordform" method="post" onsubmit="validate();">
<input type="text" name="yourpassword">
<br>
<input type="submit">
</form>
</body>
</html>
I am not sure what exactly I am missing or why it wont work but the goal of what i want is that when text is inputted into the text box named "yourpassword", a script will run that will show a message if either one of these conditions are met: shorter than 5 characters, or longer than 25, warning the person typing that their password does not follow the guidelines, if the password meets the guidelines, then i just want a simple confirmation message to appear. Anyways i appreciate any help as this is frustrating me and making me want to give up learning JS. Thanks
you need to first prevent the default behavour of form submit .
use
function validate(e)
{
e.preventDefault();
var yourpw = document.forms.passwordform.yourpassword.value.length;
... rest of code
}
Try updating your validate function to as follows:
function validate(e) {
e.preventDefault();
var yourpw = document.getElementsByName('yourpassword')[0].value.length;
if (yourpw < 5) {
alert("password is too short");
return false;
}
if (yourpw > 25) {
alert("your password is too long")
return false;
}
}
You need to grab the input fields value, as mentioned, the input field does not have a length (#Xufox) as well as prevent the default behavior for form submission.
Edit:
Full working example:
<!doctype html>
<html>
<head>
<title>Password Validator</title>
</head>
<body>
<script>
function validate(e) {
e.preventDefault();
var yourpw = document.getElementsByName('yourpassword')[0].value.length;
if (yourpw < 5); {
alert("password is too short");
return false;
}
if (yourpw > 25) {
alert("your password is too long")
return false;
}
}
</script>
<h1>Password Validator</h1>
<p>Please create a new password below</p>
<p>Be sure you password follows these guidelines</p>
<ul>
<li>No shorter than 5 characters</li>
<li>No longer than 25 characters</li>
</ul>
<br>
<form name="passwordform" method="post" onsubmit="validate(event);">
<input type="text" name="yourpassword">
<br>
<input type="submit">
</form>
</body>
</html>
Use this : but give id name yourpassword to input field .. So you can take the value easily
var yourpw = document.getElementById("yourpassword").value;
var len = yourpw.length;
If ( len < 5 )
{
alert ("this is short");
}
elseif(len>25)
{
alert(" too long")
}
else
{
//// your code
}
You can easily validate forms via RegExp.
use this function for validate 5 character limit.
var pw = document.getElementById("yourpassword").value;
function isValidatePW(PW){
var pwRegExp - /\d{5}/
return pwRegExp.test(PW);
}

Why does this think it's correct?

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)

Categories

Resources