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.
Related
New to Js and stuck here. What should I put into my if statement to insert data into database table? Because right now I do get intended error message when I submit a wrong value but it still inserts it to database. Appreciate the help!
Here is my index.js
var manageMemberTable;
$("#addMemberModalBtn").on('click', function() {
// reset the form
$("#createMemberForm")[0].reset();
// remove the error
$(".form-group").removeClass('has-error').removeClass('has-success');
$(".text-danger").remove();
// empty the message div
$(".messages").html("");
// submit form
$("#createMemberForm").unbind('submit').bind('submit', function() {
$(".text-danger").remove();
var form = $(this);
// validation
var firstname = $("#firstname").val();
var lastname = $("#lastname").val();
this is what I'm checking
if (firstname == "") {
$("#firstname").closest('.form-group').addClass('has-error');
$("#firstname").after('<p class="text-danger">The firstname field is required</p>');
}
else {
if (firstname.match(/^[a-zA-Z ]+$/) === null){
$("#firstname").closest('.form-group').addClass('has-error');
$("#firstname").after('<p class="text-danger">Firstname invalid</p>');
}
else {
$("#firstname").closest('.form-group').removeClass('has-error');
$("#firstname").closest('.form-group').addClass('has-success');
}
}
//lastname validation
if (lastname == "") {
$("#lastname").closest('.form-group').addClass('has-error');
$("#lastname").after('<p class="text-danger">The lastname field is required</p>');
}
else {
if (lastname.match(/^[a-zA-Z ]+$/) === null){
$("#lastname").closest('.form-group').addClass('has-error');
$("#lastname").after('<p class="text-danger">lastname is invalid</p>');
}
else {
$("#lastname").closest('.form-group').removeClass('has-error');
$("#lastname").closest('.form-group').addClass('has-success');
}
}
And this is the i statement
if( // Something that checks the submitted data meets requirements) {
//submit the form to server
$.ajax({
url : form.attr('action'),
type : form.attr('method'),
data : form.serialize(),
dataType : 'json',
This can be one approach.
firstname.match(/^[a-zA-Z ]+$/) returns true if the string matches the regular expression
if ((firstname != "") && (firstname.match(/^[a-zA-Z ]+$/)) &&
(lastname != "") && (lastname.match(/^[a-zA-Z ]+$/))) {
$("#firstname").closest('.form-group').addClass('has-success');
$("#lastname").closest('.form-group').addClass('has-success');
// code to send data to database
}
else {
if(firstname === ""){
$("#firstname").closest('.form-group').addClass('has-error');
$("#firstname").after('<p class="text-danger">The firstname field is required</p>');
}
if (!firstname.match(/^[a-zA-Z ]+$/)){
$("#firstname").closest('.form-group').addClass('has-error');
$("#firstname").after('<p class="text-danger">firstname is invalid</p>');
}
if(lastname === ""){
$("#lastname").closest('.form-group').addClass('has-error');
$("#lastname").after('<p class="text-danger">The lastname field is required</p>');
}
if (!lastname.match(/^[a-zA-Z ]+$/)){
$("#lastname").closest('.form-group').addClass('has-error');
$("#lastname").after('<p class="text-danger">lastname is invalid</p>');
}
}
<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>
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'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";
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