jquery code working but not the first time - javascript

I'm trying to build a small login system using jquery (since it is for testing purposes only and the user and password won't change) So i made a form and when you click the button i test whether the details are correct. if so you will get send to the next page. If not i give an alert.
It's working but i have something weird. The first time you visit the site and fill in the details it does nothing. The second time (after submitting) it works like it should.
Does someone know why?
Here is the code:
function controllogin() {
event.preventDefault();
var username = $("#gebruikersnaam").val()
var password = $("#wachtwoord").val()
if (username=="leerkrachten" && password=="leerkrachten") {
alert("welkom leerkrachten");
goToUrl();
}
else if (username=="leerling" && password=="leerling") {
alert("welkom leerling");
}
else {
alert("verkeerde gegevens ingevuld");
}
};
function goToUrl() {
alert("zoeken naar pagina");
window.location = 'leerkrachten/vakken.html';
};

Instead of onclick="controllogin();" try something like this:
$('document').ready(function() {
$('#submit').click(function(event) {
event.preventDefault();
var username = $("#gebruikersnaam").val()
var password = $("#wachtwoord").val()
if (username==="leerkrachten" && password==="leerkrachten") {
alert("welkom leerkrachten");
goToUrl();
}
else if (username==="leerling" && password==="leerling") {
alert("welkom leerling");
}
else {
alert("verkeerde gegevens ingevuld");
}
});
});
Also use === instead of == as operators to compare the strings, it prevents you from some weird results when comparing different types. Maybe that's why it doesn't work the first time, but does the second time. Otherwise I don't know why this happens.
But actually I'd have to say: NEVER do client-side login validation and NEVER do login validation with an unencrypted password (not even server-side)!

Related

Jquery issue with val not working as expected

I have a couple of forms on a site. On the first form I used the code below to add a border color if the input field is not blank and remove it if it is blank. This works just fine no issues. But I've found that when I try to use the same method on other forms, to do something else using the same logic, it does not work.
I have read through many forums and what I'm seeing is that the code is only read on page load. But I have forms that run the function after the page is far past loading. Can someone give some light to this? I'm really trying to understand the way this works fully.
Code that works on form:
var checkErrorIn;
jQuery(document).ready(function ($) {
checkErrorIn = setInterval(CheckErrorInput, 0);
});
function CheckErrorInput() {
if (jQuery('body').is('.page-id-6334')) {
// First Name, Last Name validation colors
var pasdFName = jQuery('#first_name').val();
var pasdLName = jQuery('#last_name').val();
if (pasdFName != '') {
jQuery('#first_name').addClass('formConfirm_cc');
} else {
jQuery('#first_name').removeClass('formConfirm_cc');
}
if (pasdLName != '') {
jQuery('#last_name').addClass('formConfirm_cc');
} else {
jQuery('#last_name').removeClass('formConfirm_cc');
}
if (pasdFName != '' & pasdLName == '') {
jQuery('#last_name').addClass('formError_cc');
} else {
jQuery('#last_name').removeClass('formError_cc');
}
if (pasdFName == '' & pasdLName != '') {
jQuery('#first_name').addClass('formError_cc');
} else {
jQuery('#first_name').removeClass('formError_cc');
}
}
}
Code that is not working:
if (jQuery('body').is('.woocommerce-page')) {
var checkActiveName = jQuery('.woo_login_form > form > #username').val();
jQuery('.woo_login_form').on('input', function(){
jQuery('.woo_login_form').addClass('cdc_keep_active');
});
if (checkActiveName =='') {
jQuery('.woo_login_form').removeClass('cdc_keep_active');
}
}
What I am trying to do is fix an issue with a form becoming hidden if not hovered over even when the input has characters. Based on my research I figured I'd do the .on to get the class added when the input got characters. That works but the removal of the characters isn't removing the class. The logic looks right to me. What am I missing?
Thank you in advance for your help and insight.
Update:
Ok so I ended up doing this:
jQuery('.woo_login_form').on('click', function () {
jQuery('.woo_login_form').addClass('cdc_keep_active');
});
jQuery('.custom-login-box > a').on('click', function () {
jQuery('.woo_login_form').toggle();
});
For some reason my class would not add with any of the methods suggested individually so I combined the logic. The first part adds the class that makes the form visible but then the form won't close if clicked out of regardless of the 'removeClass'. So I added a toggle (thank you commenters) method to the "hovered link" to allow users to close the box if not needed.
Would still like to understand why the first method worked in one instance but not the other. Any and all insight appreciated. Thank you.
In your current code example you immediately check for the value of the username field.
var checkActiveName = jQuery('.woo_login_form > form > #username').val();
The thing with this is that checkActiveName will never change, unless it is reassigned elsewhere in the code.
What you need to do is to check the current value after every input of the user. That means moving that line of reading the value of the input inside the input event listener.
if (jQuery('body').is('.woocommerce-page')) {
var $wooLoginForm = jQuery('.woo_login_form');
var $userName = jQuery('#username'); // This ID should only exist once, so no need for complex selectors.
$wooLoginForm.on('input', function() {
var checkActiveName = $userName.val();
if (checkActiveName =='') {
$wooLoginForm.removeClass('cdc_keep_active');
} else {
$wooLoginForm.addClass('cdc_keep_active');
}
});
}
On a sidenote: using setInterval to validate your form is a bad practice. This would basically run infinitely. It doesn't have to. You only have to check if a form is valid after the user enters a value.
Apply the same technique with the event listener like in your second code snippet.
var $document = jQuery(document);
$document.ready(function ($) {
/**
* It might even be better to listen for the input event on the form
* that has to be validated, but I didn't see it in your code.
* Right now it listens for input on the entire page.
*/
$document.on('input', CheckErrorInput);
});

ALERT Box not showing up, issue within code, not browser

I've currently created this code to check for an array (For the Login) before moving to the next array to corroborate the password. For some reason, there's a specific instance within the code preventing a javascript prompt or alert box from popping up. I've done trial and error and it appears to be an issue with the while statement overall. But, further testing is not revealing anything obvious.
while(loginSelection != true)
{
alert("Welcome to the Ballot Design Process");
var loginUsername = prompt("Please enter in your username: ");
for(checkFor; checkFor <= userID.length; checkFor++)
{
if(loginID == userID(count))
{
if(user_password == password(checkFor)
{
loginPassword = prompt("Please enter in your password: ");
}
}
else
{
arrayPos += 1;
if(arrayPos == userID.length-1)
alert("Sorry, you did not enter a correct identification.");
}
}
}
You are missing a closing bracket on your if statement:
if(user_password == password(checkFor)) <<<<<
I recommend checking your javascript code with something like http://www.jshint.com if your debugger/IDE isnt picking it up.

jQuery - validation result is different from JS Fiddle demo

I am having a very weird issue where the code of my working files doesn't work when the same code on my JS Fiddle works fine.
All I am doing is checking whether either username or password field is submitted blank.
For some reason, my working platform code doesn't pick up any input value.
I've gone through number of times, making sure that I am on same code environment
but everything is identical. I don't know where to take it from here.
(function($){
$('#signIn_1').click(function () {
var username = $('#username_1').val();
var password = $('#password_1').val();
if ( username === '' || password === '' ) {
$('.fa-user').removeClass('success').addClass('fail');
} else {
$('.fa-user').removeClass('fail').addClass('success');
}
});
})(jQuery);
Is my if statement violating any rules that might result in inconsistency?
JS Fiddle
The problem is that your <form> element is submitting, thus reloading the page. I recommend modifying the form's submit event rather than giving the button a click event, as forms are usually but not necessarily triggered by clicking the button. Also, return false is not a good way of disabling behaviour.
Example:
(function($){
$('#form_1').submit(function (event) {
var username = $('#username_1').val();
var password = $('#password_1').val();
if ( username === '' || password === '' ) {
event.preventDefault();
$('.fa-user').removeClass('success').addClass('fail');
}
else {
$('.fa-user').removeClass('fail').addClass('success');
}
});
})(jQuery);
Here's the fiddle: http://jsfiddle.net/RyanJW/VqwNw/1/
check this
use return false to stop execution
(function($){
$('#signIn_1').click(function () {
var username = $('#username_1').val();
var password = $('#password_1').val();
if ( $.trim(username) === '' || $.trim(password) === '' ) {
$('.fa-user').removeClass('success').addClass('fail');
return false;
} else {
$('.fa-user').removeClass('fail').addClass('success');
}
});
})(jQuery);
Fiddle

Using Blur and Submit events on the same form

I am still confused about this. Started learning JQuery about a week now and this is what I have:
var IsValidUserName = false;
$(document).ready(function () {
$('#txtUserName').blur(function () {
if ($('#txtUserName').val().match(isNumberLetter) &&
($('#txtUserName').val().length >= 8)) {
$('#userNameError').removeClass("error").addClass("default");
$('#txtUserName').removeClass("alert");
$('#txtUserName + label').removeAttr("id", "lblUserName");
IsValidUserName = true;
}
else {
$('#userNameError').removeClass("default").addClass("error");
$('#txtUserName').addClass("alert");
$('#txtUserName + label').attr("id", "lblUserName");
}
});
});
Lets say I have another function like above, lets say FirstName:
How do I call this on the submit event? The code works as I need it to when the user leaves a field. Not sure how I can also call this code and also use the variable above to prevent submit if the data entered is invalid.
I need to call the validation above if the user clicks the submit button and stop the submission if the IsValidUserName variable is false.
Somethings just need a little push.
Thanks my friends.
Guy
You could always extract it into a function instead of an anonymous function and pass the reference to the object you want to check. This would give you the added benefit of reusing it for other elements.
function validate(ele) {
var valid;
if (ele.val().match(isNumberLetter)) && (ele.val().length >= 8)) {
valid = true;
// update user here.
} else {
valid = false;
// update user here.
}
return valid;
}
$(function(){
$('#firstName').blur(function(){ validate($(this)); });
$('#lastName').blur(function(){ validate($(this)); });
$("yourFrom").submit(function(){
var firstNameIsValid = validate($('#firstName'));
var lastNameIsValid = validate($('#lastName'));
if (!nameIsValid) && (!lastNameIsValid) {
return false;
// User has already been updated
}
});
});
Also, since you are already heavily using javascript for your validation (hope this is convenience and not the only security), you can also disable the submit button entirely until the form meets the proper requirements.

How redirect cancel function in Javascript

I'm not a programmer. I don't want to protect with a strong secure code my page. I just need one option I'm missing in my code and can't figure out how to add it.
<script language="Javascript">
<!--
var password = "lala"
var x = prompt("","")
if (x.toLowerCase() == password) {
location = "http://google.com";
}
else {
alert("Fail")
location = "http://facebook.com"
}
//-->
</script>
As you can see it's so dump but I need it. When I press Cancel button instead of writing true or false text, website still opens. I want to include in this script cancel button function (control it, you know) whitch would redirect to another website if press on it (as it is with true or false functions). I don't want to creat a special button or an input for it.
Update: I would like to include this script in a page which i am redirecting to. Could anyone tell me:
1. How can i modify this script to make it work only once?
2. Is it anything to do with browser's cookies?
p.s. Done :)
If the user presses cancel, prompt will return null. So do like this:
if(x == null) // Cancel
{
alert('Cancel');
}
else if (x.toLowerCase() == password) { // Correct password
location = "http://google.com";
}
else { // Wrong password
alert("Fail")
location = "http://facebook.com"
}
However, I'm not sure if all browsers will return null when the user presses cancel. (I have tested in Opera)
Try
var x = prompt("","");
if( x == null || x == '')
return;
if (x.toLowerCase() == password) {
location = "http://google.com";
}
else {
alert("Fail")
location = "http://facebook.com"
}
To redirect your browser to a URL use following snippet in your Javascript:
top.location.href = "http://google.com";

Categories