Other else if statement not executed - javascript

Problem: The first conditional statement else if was performed, But the next else if statement was not performed. It should performed if both username and password are empty. What did I missed?
$(document).ready(function(){
$("#submit").click(function(e){
var username = $("#username").val();
var password = $("#password").val();
if(username == ""){
alert("account id required");
}else if(password == ""){
alert("password required!");
}else if((username == "" || username == null) && (password == "" || password == null)){
alert("All fields of information is required!");
}else{
$.ajax({
type: "POST",
url: "checklogin.php",
data: "username="+username+"&password="+password,
success:function(data){
if(data == "success"){
window.location.href="main.php";
}else if(data == "unsuccess"){
alert("Invalid account id/password");
$("#username").val('');
$("#password").val('');
}
}
});
}
return false;
});
});

If, else if, else if, else.. In this hierarchy. Any one and only one block will execute.. If your intention is to execute the second else if .. Then make it if...
So your code should be like below.
if((username == "" || username == null) && (password == "" || password == null)){
alert("All fields of information is required!");
}
else{
if(username == ""){
alert("account id required");
}else if(password == ""){
alert("password required!");
}
}

You have to put the condition containing both username and password before the other ones.

if it gets inside an if statement it wont try with the next else, so if it performs the first else if, it won't check the next else if.
you need to do something like this
if(!username && !password){
alert("All fields of information is required!");
}else if(!username){
alert("account id required");
}else if(!password){
alert("password required!");
}else{
here the rest of your code
}

Related

Javascript string comparison not detected

Sure this is a simple problem but I am new to this. Am trying to develop a simple website for a user to work out a password and then if they get it right, take them to a congrats screen where they win a prize. However my if statement is not working in the code below
<script>
function CheckPassword() {
var pword = document.getElementById("inpPassword").value;
if (pword == ""|| pword == NULL) {
alert("Please enter a password");
} else if (pword == 'newman') {
window.open('congratulations.html', '_self');
} else {
alert("Wrong password");
}
}
</script>
If I add an alert with the pword value then it prints out correctly what was entered. However the code picks up when the password input is blank, however if the input field is not blank then it does not go to the other screen or show the wrong password alert box. I have tried it with an alert box saying correct instead of the link to the new page but still did not work. Also tried using String(pword) in case that was the problem. Am sure this is a simple solution but just can't see it.
Thanks
function CheckPassword() {
var pword = document.getElementById("inpPassword").value;
if (pword == ""|| pword == null){
alert("Please enter a password");
}
else if (pword == 'newman') {
window.open('congratulations.html', '_self');
}
else
{
alert("Wrong password");
}
}
<input type='password' id='inpPassword'>
<input type='button' onclick='CheckPassword()'>
if (pword == "" || pword == null) , its null not NULL . keywords are case sensitive.
You should use null instead of NULL. Seems like it works besides of opening new window, because there is no congratulations.html in my snippet:
function CheckPassword() {
var pword = document.getElementById("inpPassword").value;
if (pword == ""|| pword == null){
alert("Please enter a password");
}
else if (pword == 'newman') {
window.open('congratulations.html', '_self');
}
else
{
alert("Wrong password");
}
}
<input id="inpPassword">
<button onclick="CheckPassword()">Click</button>
You may try here:
The mistake was here, you wrote NULL instead of null, beacuse of javascript understand null as a reserve keyword.
And use === for hard checking(data as well type checking of variaable)
function CheckPassword() {
var pword = document.getElementById("inpPassword").value;
if (pword == ""|| pword == null){
alert("Please enter a password");
}
else if (pword === 'newman') {
alert('congratulations.html', '_self');
}
else
{
alert("Wrong password");
}
}
<input type="" name="a" id="inpPassword">
<input type="button" onClick="CheckPassword()" value="check">
It seems the problem is when you compare to NULL. If you check your browser console you will likely get the following error:
Uncaught ReferenceError: NULL is not defined
That is not the correct syntax for null checks, it will look for a variable called "NULL" which you don't have. You should use null (lowercase) instead:
if (pword == ""|| pword == null){
The full adjusted code is as follows:
function CheckPassword() {
var pword = document.getElementById("inpPassword").value;
if (pword == ""|| pword == null) {
alert("Please enter a password");
} else if (pword == 'newman') {
window.open('congratulations.html', '_self');
} else {
alert("Wrong password");
}
}
Here is a working example.
Null, "" are equivalent to false in Javascript. You just have to:
if (!pword) {
alert("Please enter a password");
} else if (pword === 'newman'){
window.open('congratulations.html', '_self');
} else {
alert("Wrong password");
}
you can write null in small case so its work
function CheckPassword() {
var pword = document.getElementById("inpPassword").value;
if (pword == "" || pword == null ) {
alert("Please enter a password");
} else if (pword == 'newman') {
window.open('congratulations.html', '_self');
} else {
alert("Wrong password");
}
}
<input id="inpPassword" onblur="CheckPassword()">

Clearing specific fields (not all) when a form is submitted

Im trying to clear only the password and confirm password fields when those are not matched.
Im calling a function when the submit button is pressed which contains a password checking condition. How should I clear only password and confirmpassword inputs if that condition is true?
function checkmatch()
{
var name = $("#username").val();
var address = $("#address").val();
var email = $("#emailid").val();
var mobile = $("#phonenum").val();
var password = $("#newPwd").val();
var cnfirmPassword = $("#confirmPwd").val();
if(password != cnfirmPassword)
{
alert("Passwords do not match.");
return false;
}
else if((name==null || name == "") || (address==null || address == "") || (email==null || email == "") || (mobile=null || mobile == "") || (password==null || password == "") || (cnfirmPassword==null || cnfirmPassword == ""))
{
alert("Please fill all the required fields.");
return false;
}
else
{
$.ajax(
{
type: "POST",
url: "assmt1.php",
datatype: "html",
data: $("#fm1").serialize(),
success: function(response)
{
}
});
alert("Your form has been submitted. Thank you!");
}
}
Is this what you mean?
var password = $("#newPwd").val();
var cnfirmPassword = $("#confirmPwd").val();
if(password != cnfirmPassword)
{
alert("Passwords do not match.");
$("#newPwd").val('').focus(); ///this will not focus because of alert
$("#confirmPwd").val('');
return false;
}
All you need to do is call the same function you used to get the value.
Just pass empty string to val() like so:
$("#newPwd").val('');
$("#confirmPwd").val('');

Email validation Jquery not working

I have been working on a simple email validation. But it doesn't work.
Any ideas why it isn't working? Am I doing something wrong or should I structure my code in some other way?
I have done a function like this:
function IsEmail(email) {
var regex = /^([a-zA-Z0-9_\.\-\+])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if(!regex.test(email)) {
return false;
} else {
return true;
}
}
and after that I'm calling that function in my setupRegistration function.
My JS looks like this:
function doOutputMessage(type, message){
$("#outputMessage").html("");
$("#outputMessage").removeClass();
$("#outputMessage").hide();
if(type == "error") {
$("#outputMessage").addClass("error").fadeIn("fast");
} else if(type == "success") {
$("#outputMessage").addClass("success").fadeIn("fast");
}
$("#outputMessage").text(message);
$("#outputMessage").show();
}
function setupRegistration(){
$("#signupWrapper").on("click", "#regUser", function(){
var username = $("input[name='username']").val();
var email = $("input[type='email']").val();
var password = $("input[type='password']").val();
if(username == ""){
doOutputMessage("error", "Fill in your desired username!");
}
if(email == ""){
doOutputMessage("error", "Fill in your email!");
}
if(IsEmail(email)==false){
doOutputMessage("error", "mailen är fel förfan");
}
if(password == ""){
doOutputMessage("error", "Fill in your desired password!");
}
if(username != "" && email != "" && password != ""){
ajaxCall(username, email, password);
}
});
}
function IsEmail(email) {
var regex = /^([a-zA-Z0-9_\.\-\+])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if(!regex.test(email)) {
return false;
}else{
return true;
}
}
function ajaxCall(username, email, password){
$.ajax({
type: 'POST',
url: '../register.php',
data: {
'username' : username,
'email' : email,
'password' : password,
},
success: function(data) {
if(data.exists){
doOutputMessage("error","That Username is allready taken.");
} else if(data.inserted) {
doOutputMessage("success","You have successfully been registered!");
}else {
doOutputMessage("error","Something went wrong, try again later.");
}
}
});
}
$(document).ready(function(){
setupRegistration();
});
function regSubmit(){
clearErrorMessages();
var username = $("#regForm #username").val();
var email = $("#regForm #email").val();
var password = $("#regForm #password").val();
if(username == ""){
showValidationMessage("#regForm #error_username", "Fill in your desired username!");
}
if(email == ""){
showValidationMessage("#regForm #error_email", "Fill in your email!");
}
if(password == ""){
showValidationMessage("#regForm #error_password", "Fill in your desired password!");
}
if(username != "" && email != "" && password != ""){
$.ajax({
url: 'regLogin.code.php',
type: 'POST',
data: {
'action' : 'register',
'username' : username,
'email' : email,
'password' : password
},
success: function(data, status){
console.log(data);
if(data == "exist"){
showValidationMessage("#regForm #error_general", "A user with that username or password already exists!");
}else if(data == "illegal"){
showValidationMessage("#regForm #error_general", "Your username contains illegal characters!");
}
else if(data == "true"){
showValidationMessage("#regForm #success", "Success!");
setTimeout(function(){
window.location.replace("/admin/inside/");
}, 1000);
}
},
error: function(xhr, desc, err){
showValidationMessage("#regForm #error_general", "Something went wrong, please try again");
}
});
}
}
#Mario-Chueca is right. Your code is mostly working correctly, however, you are making an Ajax call regardless if the email is correct and as a result the error message is not shown. You should only make the ajax call when the specified email is valid:
if(username != "" && email != "" && password != "" && IsEmail(email)){
ajaxCall(username, email, password);
}
I have included a code sample below to show that your email validation (without Ajax call) is working. I have included the if(!IsEmail(email){ fix suggested by #Abdulla and I also also added a more complex regular expression from this post.
function IsEmail(email) {
//var regex = /^([a-zA-Z0-9_\.\-\+])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
//More advanced regex to valid 99.99% of most emails in use, see https://stackoverflow.com/questions/46155/validate-email-address-in-javascript
var regex = /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/;
if (!regex.test(email)) {
return false;
} else {
return true;
}
}
function doOutputMessage(type, message) {
$("#outputMessage").html("");
$("#outputMessage").removeClass();
$("#outputMessage").hide();
if (type == "error") {
$("#outputMessage").addClass("error").fadeIn("fast");
} else if (type == "success") {
$("#outputMessage").addClass("success").fadeIn("fast");
}
$("#outputMessage").text(message);
$("#outputMessage").show();
}
//if (IsEmail('john.doe#stackoverflow.com')) {
// doOutputMessage('success', 'valid email')
//}
if (!IsEmail('john.doe#stackoverflow.com')) {
doOutputMessage('error', 'invalid email')
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="outputMessage">Test</div>
Use some of the advices from before, but change this too, the error doesn't stop the ajax call:
var error_email=false;
if(!IsEmail(email)){
error_email=true;
doOutputMessage("error", "mailen är fel förfan");
}
if(password == ""){
doOutputMessage("error", "Fill in your desired password!");
}
if(username != "" && email != "" && password != "" && !error_email){
ajaxCall(username, email, password);
}
remove false in here
if(!IsEmail(email){
and regex should be
regex = /^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
Live DEMO
How to Find or Validate an Email Address
please try:
function IsEmail(email){
var reg = /^[a-zA-Z0-9\.\-\+]+\#([a-zA-Z0-9\-]+\.)+[a-zA-Z0-9]{2,4}$/
return reg.test(email)
}

How to call the next page after button login clicked in XDK

In my login script when the username and password are both correct it must go to the next page (main/menu page) of the intel XDK.
My problem is how or what code can I use to call the next page whenever the username and password is correct (login successful)?
function validateForm() {
var formUsername = document.forms.login.username.value;
var formPassword = document.forms.login.password.value;
var MINLENGTH = 5;
// Validate username and password
if (formUsername === null || formUsername === "") {
alert("Username must be filled out");
}
else if (formPassword === null || formPassword === "") {
alert("Password must be filled out");
}
else if (formUsername.length < MINLENGTH || formPassword.length < MINLENGTH) {
alert("The minimum length of username and password at least " + MINLENGTH);
}
else if(formUsername == 'admin' && formPassword == 'admin'){
alert('welcome');
//this is where should i put the code to go at the next page of the XDK API.
return;
}
alert("Login failed!!!");
}
got it guys..
it will be.. like this ..
else if(formUsername == 'admin' && formPassword == 'admin'){
alert('welcome');
activated_page("#menu");
return;
}

JavaScript Load New Page Question

What I am looking to do is if a user complete a form it will provide access to a new location.
<script language="JavaScript" type="text/javascript">
<!--
function validateForm(theForm) {
var firstname = theForm.firstname.value;
var lastname = theForm.lastname.value;
var email = theForm.email.value;
if (firstname == "") {
alert("Please fill in your First Name.");
theForm.firstname.focus();
return false;
}
if (lastname == "") {
alert("Please fill in your Last Name.");
theForm.lastname.focus();
return false;
}
if (email == "") {
alert("Please fill in your email address.");
theForm.email.focus();
return false;
}
return true;
}
I know this part is wrong but I have no idea how to go about doing it. any help would be nice..
if lastname=""
if firstname=""
if email=""
load('www.google.com');
if (validateForm(theForm)) window.location = 'http://www.google.com';
Is equivalent to using
if (validateForm(theForm)) window.location.href = 'http://www.google.com';
Both will work, so choose which one you prefer.
if lastname=""
if firstname=""
if email=""
load('www.google.com');
becomes
if ((lastname == "") && (firstname == "") && (email == "")) {
window.location = "http://www.google.com";
}

Categories

Resources