I'm trying to set up a form that allows you enter a password that grants access to a specific URL.
For example, enter "facebook", and it takes you to www.facebook.com Enter, "yahoo", it sends you to www.yahoo.com Enter, "google",.... you get it. If one enters anything but those words, it gives an error.
This is what I have so far:
<script language="javascript">
<!--//
/*This Script allows people to enter by using a form that asks for a
UserID and Password*/
function pasuser(form) {
开发者_StackOverflow中文版 if(form.id.value=="google") { location="http://www.google.com" }
else if(form.id.value=="facebook") { location="http://www.facebook.com" }
else if(form.id.value=="yahoo") { location="http://www.yahoo.com" }
else {alert("Invalid Password")}
}
//-->
</script>
<form name="login">
<input name="id" type="text">
<input type="button" value="Enter Class" onClick="pasuser(this.form)">
</form>
However, this doesn't work! Can someone help me set this up! I'd really like to have more than 3 options.
Thanks!
I don't know what doesn't work in this particular example (it works, on clicking submit button, not hitting ENTER). But if you want to have more than 3 sites, you could make it easier:
<script>
// ...
sites = {
"google": "http://www.google.com",
"facebook": "http://www.facebook.com",
"yahoo": "http://www.yahoo.com"
};
function pasuser(form) {
if (sites[form.id.value]) {
window.location = sites[form.id.value];
} else {
alert("Invalid Password")
}
}
</script>
You shouldn't use "id" as the name of an HTML element since it may conflict with the id
property. For the rest of my answer, look at MBO's answer
If you're wanting to send your user to a specific location, you might want to use window.location
instead of just location
.
I think you meant to write something along the lines of this:
function redirect( ) {
var textfield = document.getElementById( 'textfield' );
var location = '#';
switch( textfield.value ) {
case 'facebook':
location = 'http://facebook.com';
break;
case 'google':
location = 'http://google.com';
break;
// add as many as you like
}
window.location.href = location;
}
HTML:
<input id="textfield" type="text" value=""/>
<input type="button" value="Enter Class" onclick="redirect()"/>
You do not need a form to do this URL redirection.
Good luck.
I tried your code on Firefox 3.5 and IE 8 and it works when you click the button, not when you hit Enter after typing the string. To make it work from enter key, call return pasuser(this)
from the onsubmit of the form and return false;
from end of the pasuser function.
<form name="login" onsubmit="return pasuser(this)">
function pasuser(form)
{
//other code
else {alert("Invalid Password")}
return false;
}
精彩评论