I'm new to JavaScript, but I followed a really good tutorial, and I'm making a sign in pop-up form, but it doesn't work... The idea is that you have one username, and one password, if both are correct, you will redirect to a page. I lost the HTML code for the form, but with an input field, the id has to be uName, and with the password field pWord. Here's my JavaScript code:
function myFunction(){
var uName = document.getElementById("uName").value;
var pWord = document.getElementById("pWord");
}
// This line controls the uName and pWord.
if(uName = "Admin",pWord = "Admin"){
// This line creates a pop-up with the name.
alert("Welcome " + uName);
// Need a line to redirect to a new page
// Need a line with the else statement
// Need a line to say if something if not all fields are filled
}
The username has to be Admin and the password Admin. If you don't enter the right combination, you have to get a message like: "Incorrect combination.".
There's a couple of issues:
You're not getting the value of the password field, but the object
You're not validating the credentials inside the function
You are assigning "Admin" to uName and pWord with a single =
You need to use && to match both tests of your if statement
As a side note: You should never validate a login with the username and password hardcoded like this, it is always avaiable to the user, all you would need to do is right click in browser and view source to see the username and password - this login script is fine for learning how javascript works, but don't implement a login like this in the real world unless it is purely a crawler type deterrent
= sets a value, == matches the value, === matches the value and type (string, object, int)
function myFunction(){
var uName = document.getElementById("uName").value;
var pWord = document.getElementById("pWord").value;
// This line controls the uName and pWord.
if(uName == "Admin" && pWord == "Admin"){
// This line creates a pop-up with the name.
alert("Welcome " + uName);
// Need a line to redirect to a new page
// Need a line with the else statement
// Need a line to say if something if not all fields are filled
}
}
To combat your comments
// Need a line to redirect to a new page
window.location.href="/pagetoredirectto.html";
and
// Need a line with the else statement
if(uName == "Admin" && pWord == "Admin"){
alert("Welcome " + uName);
} else {
alert( "User and Pass do not match" );
}
and this should go just after you get the values.. so the full code is at the bottom of this answer
// Need a line to say if something if not all fields are filled
if( !uName || !pWord )
{
alert( "Enter both a username and password" );
return;
}
We use a return here to stop the rest of the function from executing
Full Code
function myFunction(){
var uName = document.getElementById("uName").value;
var pWord = document.getElementById("pWord").value;
// Need a line to say if something if not all fields are filled
if( !uName || !pWord )
{
alert( "Enter both a username and password" );
return;
}
// This line controls the uName and pWord.
if(uName == "Admin" && pWord == "Admin"){
alert("Welcome " + uName);
window.location.href="/pagetoredirectto.html";
} else {
alert( "User and Pass do not match" );
}
}
This is assignment with = operator:
if (uName = "Admin",pWord = "Admin") {
While you need comparison == or ===:
if (uName == "Admin" && pWord == "Admin") {
Also usage of the comma , operator is not correct (well it is correct, but not in this place). You need logical AND &&.
Assignment inside of if check makes truthy expression ("Admin" string is truthy), making code always enter if-block.
Change your code as below and check:
function myFunction(){
var uName = document.getElementById("uName").value;
var pWord = document.getElementById("pWord").value;
if(uName != "" && pWord != ""){ /* Ensure both fields have value */
if(uName == "Admin" && pWord == "Admin"){
alert("Welcome " + uName);
/* Redirection code goes here */
}else{
/* If user is not Admin */
}
}else{
/* Validation message goes here */
}
}
Thats it i Hope:
function myFunction(){
var uName = document.getElementById("uname").value;
var pWord = document.getElementById("pWord").value;
if (uName == "Admin" && pWord == "Admin") {
// This line creates a pop-up with the name.
alert("Welcome " + uName);
// Need a line to redirect to a new page
document.location = "http://www.google.de"
// Need a line to say if something if not all fields are filled
}else if (uName == "" || pWord == "") {
alert("Fill all fields");
// Need a line with the else statement
}else{
alert("Incorrect Combination");
}
}
<input id="uname"></input>
<input id="pWord"></input>
<input type="button" onclick="myFunction()" value="Login"></input>
Still a way to insecure Version of a login script.
If you go to debug you can see username and pass in cypher text plain insecurity.
Well try this example:
function myFunction(){
var uName = document.getElementById("uName").value;
var pWord = document.getElementById("pWord").value;
// This line controls the uName and pWord.
if(uName == "Admin" && pWord == "Admin"){
// This line creates a pop-up with the name.
alert("Welcome " + uName);
// Need a line to redirect to a new page
location.href = "http://www.SOMEURL.com";
// Need a line with the else statement
} else {
// Need a line to say if something if not all fields are filled
alert("Wrong input");
}
}
You are taking reference of particular whole object in var pWord though you intend to take only value of password field.
Also You are assigning "Admin" to uName and pWord with the single =. For comparison use === or == though I would recommend use of ===.
Do this:
function myFunction(){
var uName = document.getElementById("uName").value;
var pWord = document.getElementById("pWord").value;
}
For redirection use
window.location = "http://www.location.com/ie.htm";
Related
<script language="javascript">
function check(form)
{
if(form.userid.value == "username1" && form.pswrd.value == "password1" || form.userid.value == "username2" && form.pswrd.value == "password2" || form.userid.value == "username3" && form.pswrd.value == "password3")
{
window.open('http://www.youtube.com')
}
else
{
alert("hello rising field student, your password or username is wrong!")
}
}
</script>
Here is a code I have written in javascript, it actually takes a user to www.youtube.com after a successful login. I want a situation where each user would be assigned a specific url so when they login, they would be taken to that url. Thanks to anyone who would be very helpful in this case.
You can use an if condition for each URL which should be passed to window.open() for the specific user, and use a variable set to boolean true or false if either of the if conditions which checks form elements values evaluates to true
<script language="javascript">
function check(form) {
var username = form.userid.value;
var password = form.pswrd.value;
var validUser = false;
if (username == "username1" && password == "password1") {
validUser = true;
window.open("/path/to/url/1")
}
if (username == "username2" && password == "password2") {
validUser = true;
window.open("/path/to/url/2")
}
if (username == "username3" && password == "password3") {
validUser = true;
window.open("/path/to/url/3")
}
if (!validUser)
alert("hello rising field student, your password or username is wrong!")
}
}
</script>
I need help in validating the response of ReCaptcha in javascript validation which is made for other validations like, n Field is empty etc..
The javascript function function verify(f) {....} get called on onSubmit="return verify(this);" in html <form name="form2" method="POST" action="alink.asp" onSubmit="return verify(this);">
Bellow is the complete js function:
function verify(f) {
var msg = '';
var s = f.CKRoutingNumber.value;
s = s.replace(/[^0-9]/gi, "");
f.CKRoutingNumber.value = s;
if (f.CustomerID.value == '') { msg = 'Please enter your Bricks R Us Customer ID.'; f.CustomerID.focus(); }
else if (f.PurchaseOrderNumber.value == '') { msg = 'Please enter the purchase order number.'; f.PurchaseOrderNumber.focus(); }
else if (f.Amount.value == '') { msg = 'Please enter the amount you wish to pay.'; f.Amount.focus(); }
else if (f.CKBankName.value == '') { msg = 'Please enter a value into the Bank Name field.'; f.CKBankName.focus(); }
else if (f.CKRoutingNumber.value == '') { msg = 'Please enter a value into the Routing Number field.'; f.CKRoutingNumber.focus(); }
else if (s.length != 9) { msg = 'Please enter a valid nine-digit routing/transit number.'; f.CKRoutingNumber.focus(); }
else if (f.CKAccountNumber.value == '') { msg = 'Please enter a value into the Account Number field.'; f.CKAccountNumber.focus(); }
else if (f.CKNumber.value == '') { msg = 'Please enter a value into the Check Number field.'; f.CKNumber.focus(); }
else if (f.BillingName.value == '') { msg = 'Please enter a value into the Full Name field.'; f.BillingName.focus(); }
else if (f.BillingAddress.value == '') { msg = 'Please enter a value into the Billing Address field.'; f.BillingAddress.focus(); }
else if (f.BillingCity.value == '') { msg = 'Please enter a value into the Billing City field.'; f.BillingCity.focus(); }
else if (f.BillingState.value == '') { msg = 'Please select a value for the Billing State field.'; f.BillingState.focus(); }
else if (f.BillingZIPCode.value == '') { msg = 'Please enter a value into the Billing ZIP Code field.'; f.BillingZIPCode.focus(); }
else if (f.BillingPhone.value == '') { msg = 'Please enter a value into the Phone Number field.'; f.BillingPhone.focus(); }
if (msg != '') {
alert(msg);
return false;
}
}
The above function is on the same page in which the form is made.
Bellow is the ASP classic code which get response from reCaptcha. Its also on the same page
<%
Dim reresponse
reresponse= Request.form("g-recaptcha-response")
Dim VarString
VarString = _
"?secret=6Lex3CMTAAAAAASVS5XnIq4Ya5ZGvEH_W70NU&" & _
"&response=" & reresponse & _
"&&remoteip=" & Request.ServerVariables("REMOTE_ADDR")
Dim url
url="https://www.google.com/recaptcha/api/siteverify" & VarString
Dim objXmlHttp
Set objXmlHttp = Server.CreateObject("Msxml2.ServerXMLHTTP")
objXmlHttp.open "POST", url, False
objXmlHttp.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
objXmlHttp.send
Dim ResponseString
ResponseString = objXmlHttp.responseText
Set objXmlHttp = Nothing
If instr(ResponseString, "success" & chr(34) &": true")>0 then
// do nothing
else
// Here I want to get this response message and validate it in the above javascript function.
end if
%>
I'm confused that how can I get the response from asp and validate it in the verify(f) javascript function so that I also get alert message on submit button that the recaptcha is required and or incorrect.
My intention is to validate the reCaptcha response in same veryify javascript function which get called on submit and shows validation in alert()
Remember, both asp code and javascript code are in the same page.
Please ask if you also need my form html code
Your verify() function is running locally and doing some input value checking/alerting is OK, but in any case you should check whatever comes from the browser on de server side. If you would send the ReCaptscha response back to that verify() function you undermine your security because your users could simple change that verify() function ...
function repasswordvalid()
{
var cpassword = document.registration.repassword.value;
var passwordchk = document.registration.password.value;
if((passwordchk != cpassword) && cpassword == "")
{
alert("Cofirm password not matched..!!");
document.getElementById('repassword1').innerHTML = "The password is required.";
document.getElementById('repassword1').focus();
}
else
{
document.getElementById('repassword1').innerHTML = "";
}
}
Here I am checking for confirm password validation onBlur event. All fields are working but here i am stuck.
You probably want an or in your condition not an and, since the cpassword will have to be blank and both field mismatched for the alert to trigger
if((passwordchk != cpassword) || cpassword == "")
I've created a login script with JQuery that when the values of username and password equal the Username and Password values in localstorage (they are stored when hitting "Register"), it hides the login div and shows a div called 'accent'. However no matter what I do in the javascript, the login page persists and the accent page never shows.
I've created a jsfiddle that shows that I mean:
http://jsfiddle.net/CR47/bpztq/
Here is the code for the login button:
$('#loginButton').click(function(){
if(localStorage.getItem('Username') != null || localStorage.getItem('Username') != ''){
var cu = localStorage.getItem('Username');
var cp = localStorage.getItem('Password');
alert(cu);//I've alerted to show that the getItem is working
alert(cp);
var iu = $('#username').val();
var ip = $('#password').val();
if(iu == cu && ip == cp){
$('#login').hide(0);
$('#accent').show(0);
localStorage.setItem('Logged In', 'yes');
$('#name').val() == localStorage.getItem('Name');
$('#gender').val() == localStorage.getItem('Gender');
$('#age').val() == localStorage.getItem('Age');
$('#address').val() == localStorage.getItem('Address');
$('#phone').val() == localStorage.getItem('Phone');
$('#email').val() == localStorage.getItem('Email');
}else{
alert('Incorrect username/password combo.');
}
}
});
The "logged in" value for localstorage does set to yes.
The problem is that the form is submitted after $('#loginButton') is clicked and so the page reloads. To prevent it, you can add preventDefault() on your Click event.
$('#loginButton').click(function(e){
e.preventDefault();
if(localStorage.getItem('Username') != null || localStorage.getItem('Username') != ''){
var cu = localStorage.getItem('Username');
var cp = localStorage.getItem('Password');
alert(cu);//I've alerted to show that the getItem is working
alert(cp);
var iu = $('#username').val();
var ip = $('#password').val();
if(iu == cu && ip == cp){
$('#login').hide(0);
$('#accent').show(0);
localStorage.setItem('Logged In', 'yes');
$('#name').val() == localStorage.getItem('Name');
$('#gender').val() == localStorage.getItem('Gender');
$('#age').val() == localStorage.getItem('Age');
$('#address').val() == localStorage.getItem('Address');
$('#phone').val() == localStorage.getItem('Phone');
$('#email').val() == localStorage.getItem('Email');
}else{
alert('Incorrect username/password combo.');
}
}
});
You need to prevent reloading page, in:
$('#loginButton').click(function (e){
Add e.preventDefault();
As well you need to assign variables not compare them, change:
$('#age').val() == localStorage.getItem('Age');
to:
$('#age').val() = localStorage.getItem('Age');
BTW, this SO post may be helpful for you - Difference between == and === in JavaScript
I am trying to pass a user name and password through a dynamically created form but it's not doing so. Here's the JS. The dynamically created form is only if the url contains certain url stems ( location.pathname...3rd "if" statement) Any ideas? It's driving me crazy.
function PostToAccountManagement() {
var userName = $('#Username').val();
var passWord = $('#Password').val();
if (userName == "")
$('#UsernameError').html('Please enter a valid username');
else
$('#UsernameError').html('');
if (passWord == "")
$('#PasswordError').html('Please enter a valid password');
else
$('#PasswordError').html('');
if (location.pathname.search(/\/info/i) == 0 ||
location.pathname.search(/\/blogs/i) == 0 ||
location.pathname.search(/\/groups/i) == 0 ||
location.pathname.search(/\/askquestion/i) == 0) {
$('<form id="Form1"> </form>').prependTo('body');
if (userName != "" && passWord != "") {
document.cookie = "ReturnUrl" + "=" + window.location.href;
$('#Form1').eq(0).attr('action', '/account/logon');
$('#Form1').eq(0).attr('method', 'post');
$('#Form1').submit();
}
}
if (userName != "" && passWord != "") {
document.cookie = "ReturnUrl" + "=" + window.location.href;
$('#Form1').eq(0).attr('action', '/account/logon');
$('#Form1').eq(0).attr('method', 'post');
$('#Form1').submit();
}
}
First the form you creates in the 3rd "if". Looks like you already have a form with id "Form1", this is not good.
Second you can't get the username and password when the 3rd "if" is triggered because the form you submit don't have elements named like that, it actually have none. Try adding at least some hidden inputs properly named.