In Javascript IF-ELSE, IF Statement is not working - javascript

I am trying to work on verifying OTP. Here I have two components that are:
Textbox which takes input of OTP. id="txtOTP"
An Status Line (here i have used <i> tag) that shows status of verified OTP. id="statusLine"
I am using JavaScript for this purpose.
function checkOTP()
{
var OTP = "1234";
var txtOTP = document.getElementById('txtOTP');
var statusLine = document.getElementById('statusLine');
var myOTP = txtOTP.value;
if (OTP.value == myOTP)
{
console.log('Entered in Valid OTP');
statusLine.style.display = "inline";
statusLine.style.color = "green";
statusLine.innerHTML = "OTP Verified, Generating Your Pass and Redirecting to the Next Page... ";
console.log('Exit From Valid OTP');
return true;
}
else if (OTP.value != myOTP)
{
console.log('Entered in Invalid OTP');
statusLine.style.display = "inline";
statusLine.style.color = "red";
statusLine.innerHTML = "Invalid OTP. Please Try Again";
console.log('Exit From Invalid OTP');
return false;
}
}
As Per my code it should go to the if's scope if OTP is correct, and it should go to the else's scope if OTP is wrong.
However, it always goes to the else's scope even though I am writing the correct OTP in the textbox. I have even tried this code without using if with the else statement (like else if() { } ).

You need to either change myOTP to a number or use double equals:
var myOTP = parseInt(txtOTP.value);
Or:
if (OTP == myOTP) {...}
Also note that you don't need else if (...) - just use else {...}.

OTP is a Number but you check OTP.value in if/else if statements
function checkOTP()
{
var OTP = 1234;
var txtOTP = document.getElementById('txtOTP');
var statusLine = document.getElementById('statusLine');
var myOTP = txtOTP.value;
if(OTP === myOTP )
{
console.log('Entered in Valid OTP');
statusLine.style.display = "inline";
statusLine.style.color = "green";
statusLine.innerHTML = "OTP Verified, Generating Your Pass and Redirecting to the Next Page... ";
console.log('Exit From Valid OTP');
return true;
}
else if(OTP != myOTP )
{
console.log('Entered in Invalid OTP');
statusLine.style.display = "inline";
statusLine.style.color = "red";
statusLine.innerHTML = "Invalid OTP. Please Try Again";
console.log('Exit From Invalid OTP');
return false;
}
}

Here is a solution. Its based on the comments and previous answers:
function checkOTP() {
var OTP = "1234";
var txtOTP = document.getElementById('txtOTP');
var statusLine = document.getElementById('statusLine');
var myOTP = txtOTP.value;
if (OTP == myOTP) {
console.log('Entered in Valid OTP');
statusLine.style.display = "inline";
statusLine.style.color = "green";
statusLine.innerHTML = "OTP Verified, Generating Your Pass and Redirecting to the Next Page... ";
console.log('Exit From Valid OTP');
return true;
} else {
console.log('Entered in Invalid OTP');
statusLine.style.display = "inline";
statusLine.style.color = "red";
statusLine.innerHTML = "Invalid OTP. Please Try Again";
console.log('Exit From Invalid OTP');
return false;
}
}
You needed to write OTP instead of OTP.value and you don't need and else if for the opposite. Just else will do.

try adding a else statement after the else if since the syntax is :
if (condition1) {
// block of code to be executed if condition1 is true
} else if (condition2) {
// block of code to be executed if the condition1 is false and condition2 is true
} else {
// block of code to be executed if the condition1 is false and condition2 is false
}

Related

I am trying to use use this validation in my html tag by using onsubmit=return validateForm()

//this is the javascript program for validation
function validateForm()
{
var name=document.myform.uname.value;
var password=document.myform.password.value;
var conpass = document.myform.repassword.value;
boolean valid = true;
if(password != conpass)
{
alert("password is not same");
valid=false;
}
else if(name==null || name=="")
{
alert("User Name should not be blank..");
valid=false;
}
else if(password==""|| password==null)
{
alert("Password should not be blank");
valid=false;
}
else if(!this.form.checkbox.checked)
{
alert('You must agree to the terms first.');
return false;
}
else{
return valid;
}
};
//and this is the html in which I am using this but it is not working properly,it is not taking the js validation and directly forwarding me to the reg.jsp page.
<form action="reg.jsp" name="myform" method="post" onsubmit="return validateForm()" >
In order to prevent submit via javascript, you have to return false in your onsubmit handler.
So the in the following line the validateForm() must return false:
<form action="reg.jsp" name="myform" method="post" onsubmit="return validateForm()" >
You have many if-else blocks that set the var valid = false and this is ok.
But this valid variable should be returned. You do this only in the last else blocks.
else if(!this.form.checkbox.checked)
{
alert('You must agree to the terms first.');
return false;
}
else{
return valid;
}
The previous checks are just preparing the variable, but don't return it.
And this is what you need to do.
Here is an example how it can be done:
function validateForm() {
var name=document.myform.uname.value;
var password=document.myform.password.value;
var conpass = document.myform.repassword.value;
var valid = true;
var message = "everything is valid";
if(password != conpass)
{
message = "password is not same";
valid = false;
}
else if(name==null || name=="")
{
message = "User Name should not be blank..";
valid = false;
}
else if(password==""|| password==null)
{
message = "Password should not be blank";
valid = false;
}
else if(!this.form.checkbox.checked)
{
message = "You must agree to the terms first.";
valid = false;
}
alert(message);
return valid;
};
Other improvement could be:
Reordering the conditions by descending importance.
For example: if the Term are not accepted, is not important, if the password is empty.
If password is empty, it is not important, if the conpass is the same.
Using html5, which hast more input types and adjustable build-in validation for common cases. See more here: http://html5doctor.com/html5-forms-input-types/

Prompt box to re-create itself until correct field has been entered

I've got some code for a Javascript alert. I want my client to be able to enter a code to access an area of my website.
At the moment I have some JS code that if a user enters the wrong credentials an alert box is created and a user selects okay and it goes to the website anyway. This is not ideal.
How can I have a loop that re-creates the prompt box until the correct credential (variable x) is supplied.
window.onload = function launch() {
var x = "name of credential";
var person = prompt("The website is under development\nPlease enter your development code:");
if (person == x) {
alert("Success!");
<?php header("Location : index.php");?>
}
else {
alert("You have entered the wrong credentials please try again!");
var person = prompt("The Care Socierty website is under development\nPlease enter your development code:");
}
Krishna's suggestion
window.onload = function launch() {
var x = "credential";
var person = prompt("The website is under development\nPlease enter your development code:");
if (person == x) {
alert("Success!");
window.location;
}
else {
alert("You have entered the wrong credentials please try again!");
return false;
}
}
Make a loop in order to iterate you code
Try this one it might help you
window.onload = function () {
var x = "name of credential";
var wrong = true;
while (wrong) {
var person = prompt("The website is under development\nPlease enter your development code:");
if (person == x) {
alert("Success!");
wrong = false;
<?php header("Location : index.php");?>
}
}
}
Just try with:
if (person == x) {
alert("Success!");
window.location = 'index.php';
} // ...
If you need to keeps prompting you need to do something like this.
Try here : http://jsbin.com/duroguji/2/edit
$(function () {
setTimeout(askPermission,1000);
});
function askPermission()
{
var success = false;
var x = "HELLO";
while(!success)
{
var person = prompt("The website is under development\nPlease enter your development code:", "");
if (person == x) {
success = true;
alert("Success!");
}
else {
alert("You have entered the wrong credentials please try again!");
setTimeout(askPermission,1000);
}
}
}

javascript validation with regex breaking all javascript

I'm writing javascript to validate a business calculator / orderform
another team mate has written the math code, but when I put in my code the whole thing stops.
I can't find my error (I'm more a css/html person)
help?
//Order Detail Variables//
var clientname =document.getElementById(clientname);
var phonenumber =document.getElementById(phoneno);
var deliveryaddress=document.getElementById(deliveryaddress);
var suburb =document.getElementById(suburb);
var postcode =document.getElementById(postcode);
var state =document.getElementById(state);
var deliverydistance = document.getElementById(deldistance);
var bagsordered =document.getElementById(bagsordered);
var orderdetailsarray = new Array();
//validation//
// these are boolean variables that when made true//
//by the validation will allow the calculation and logging to occur//
var clientnamevalid = new Boolean(false);
//Regex Variables//
//these are the regex patterns that are used to //
//confirm that the data is valid//
var alpha = pattern=/^[a-zA-Z\-]+$/;
function validation()
{
function validation();
{console.log (clientname);
if(alpha.test(clientname));
var clientnamevalid = true;
if { clientnamevalid = true;
alert(client name valid); //to be replaced with inline alert
}
else {
alert("client name invalid");
}
}
Edit Updated code:
the vars are now
var clientname =document.getElementById('clientname');
the function:
function validation()
{console.log (clientname);
var clientnamevalid = alpha.test(clientname);
if(clientnamevalid);
{
alert('client name valid')
}
else
{
alert("client name invalid");
}
}
Edit Updated code 2:
<button name="calculate" id="calcbutton" onclick="validate()"> Calculate </button>
function validate()
{console.log (clientname);
var clientnamevalid = alpha.test(clientname);
if(clientnamevalid);
{
alert('client name valid');
}
else
{
alert("client name invalid");
}
if clientnamevalid = true;
{
function calculateorder();
}
}
edit 3:
function validate()
{console.log (clientname);
var clientnamevalid = alpha.test(clientname);
if(clientnamevalid);
{
alert("client name valid"); //edited from single quotations
}
else
{
alert("client name invalid");
}
if (clientnamevalid == true);
{
calculateorder();
}
else
{
alert ("please review form");
}
}
calc order func:
function calculateorder()
{
orderdetailsarray [0] = document.forms["orderform1"] ["clientname"].value;
orderdetailsarray [1] = document.forms["orderform1"] ["phoneno"].value ;
orderdetailsarray [2] = document.forms["orderform1"] ["deliveryaddress"].value;
orderdetailsarray [3] = document.forms["orderform1"] ["suburb"].value;
orderdetailsarray [4] = document.forms["orderform1"] ["postcode"].value;
orderdetailsarray [6] = parseFloat(document.forms["orderform1"] ["deldistance"].value);
orderdetailsarray [7] = parseFloat(document.forms["orderform1"] ["bagsordered"].value);
orderdetailsarray [8] = document.forms["orderform1"] ["orderdate"].value;
//gross calculation
var grossbagcost = orderdetailsarray[7] * millendcost;
grossbagcost = Math.round(grossbagcost *100)/100;
document.forms["resultsform"] ["bagsgross"].value = grossbagcost;
//end gross calculation
//discount amount calculation
if (orderdetailsarray [7] <=50)
{
var discountedbagcost = grossbagcost * discountnil;
document.forms["resultsform"] ["discount"].value = discountedbagcost;
}
else if (orderdetailsarray[7] >50 && orderdetailsarray[7] <100)
{
var discountedbagcost = grossbagcost * discount4percent;
discountedbagcost = Math.round(discountedbagcost *100)/100;
document.forms["resultsform"] ["discount"].value = discountedbagcost;
}
else if (orderdetailsarray[7] >=100)
{
var discountedbagcost = grossbagcost * discount7percent;
discountedbagcost = Math.round(discountedbagcost *100)/100;
document.forms["resultsform"] ["discount"].value = discountedbagcost;
}
updated code with null check
function validate()
{console.log (clientname);
//pattern test
var clientnamevalid == alpha.test(clientname);
if(clientnamevalid);
{
alert("client name valid");
}
else
{
alert("client name invalid");
//null check
}
if (x==null || x=="")
{
alert("Client name cannot be left blank");
clientnamenotnull == false;
}
else
{
clientnamenotnull == true;
}
//is the whole form valid
{
if (clientnamevalid == true)
if (clientnamenotnull) == true)
{
calculateorder();
}
else
{
alert ("please review form");
}
}
This appears to be problem area:
function validation()
{
function validation();
You have function inside another function.
Your function validation() is one big bug.
Did you mean
function validation(clientname)
{
console.log (clientname);
var clientnamevalid = alpha.test(clientname);
if (clientnamevalid)
{
alert('client name valid');
}
else
{
alert("client name invalid");
}
}
And you don't call that function in your code. And remember, parentheses and curly braces position does matter.
Another one, adding to anubhava's answer you need to change all getElementById from
document.getElementById(deldistance);
to
document.getElementById('deldistance');
In addition to anubhava and Surender,
the document.getElementById() get string.. so you need to change all this
//Order Detail Variables//
var clientname =document.getElementById(clientname);
var phonenumber =document.getElementById(phoneno);
var deliveryaddress=document.getElementById(deliveryaddress);
var suburb =document.getElementById(suburb);
var postcode =document.getElementById(postcode);
var state =document.getElementById(state);
var deliverydistance = document.getElementById(deldistance);
var bagsordered =document.getElementById(bagsordered);
and write the parameters between quotes.
for example:
var bagsordered = document.getElementById('bagsordered');
because as you wrote it, it confuse the compiler.
you can't pass the variable you just declare now at the same line you want his id.
if you're a css/html person as you say, you know that when you create an html button or div
you can define his id.
like <input type="button" id="order" value="press to order" />
now in javascript you can add functionality to this button. so when you want to get
this button in javaScript you can use the function document.getElementById('order')
see? I gave the id of the button that was declared in the html code.
hope you understand what i mean
Edit
look, when you have a button, as you said. for example i'll use the button I wrote before.
<input type ="button" id="order" value="press to order"/>
now if I have a function called "function()";
and I want that when the user will press on the button the function will be called
so I'll add to the html code of the button the onclick
so now it will be :
<input type = "button" id="order" value ="press to order" onclick="function()"/>
now when the user will click on that button, the function will be called and the code in it will performed
in addition, when you write a function that will change some label or button text.
you will need to get theirs id.
if my function is "changeText()". and I have a button with value "Hello" and id = "btn"
and I want to change the button value's from "Hello" to "wow"
so I need to get that button right?
and how do I get it?
with the method document.getElementById
here is the code:
function changeText()
{
var btn = document.getElementById('btn');
btn.value = "wow";
}
Edit 2:
clientnamevalid is boolean,right?
so when you want to check if it true or false, you can use the if statement.
if (clientnamevalid == true)
{
// do something, like call to calculateorder
calculateorder();
}
else // it's false
{
// do something else
}
note that you don't have to compare the 'clientnamevalid' variable or all another boolean variable to 'true' or 'false', the if statement does it alone. so you can write
if (clientnamevalid) // means that the clientnamevalid is true
{
calculateorder();
}
else
{
// do something else
}
Edit 3:
** From where you get the client name?! you need to enable the user to enter his name..
So you need a Form.. **
function validate()
{
console.log (clientname);
if (clientname != "" || clientname != null)
{
var clientnamevalid = alpha.test(clientname);
if(clientnamevalid)
{
alert("client name valid");
calculateorder();
}
else
{
alert("client name invalid, please review form");
}
}
else
{
alert("client name can't be empty!");
}
}

Javascript validation of login form - field must be not blank and contain a "\"

Here is the code I have now.
function ns_check()
{
var login = document.forms['vpnForm'].login.value;
var passwd = document.forms['vpnForm'].passwd.value;
var domainname = login.indexOf("\\")
if (domainname = - 1){
window.alert(_("You need to enter a domain name")); return false;
}
if (login == ""){
window.alert(_("You need to enter login name")); return false;
}
if (passwd == ""){
window.alert(_("You need to enter passwd")); return false;
}
return true;
}
When you do not use a backslash in the login box it does popup an alert window, but it is empty.
Any help would be appreciated.
if (domainname = - 1)
should be
if (domainname === - 1)

javascript problems when another javascript added

I have the following script that works fine until I add the other javascript below...
First Script in the header tags
function validateForm() {
var valid = true;
var errMsg = "";
var email = document.emailform.email.value;
var filter = /^([a-zA-Z0-9_.-])+#(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
if(email.length <= 0) {
valid = false;
errMsg += "Email address is required.\n";
} else {
if (!filter.test(email)) {
valid = false;
errMsg += "Please provide a valid email address.\n";
}
}
if (errMsg.length > 0) {
alert(errMsg);
return false;
}
}
and just before the closing tags I have...
$('#form').submit(validateForm);
The above works fine, except once I add the script below, validateForm no longer works. This following is added just before the closing body tags.
cbr202=Math.random()*10000000000000000;document.write('<scr'+'ipt language="JavaScript" src="http://example.com/landing.php?lpip=411&202cb='+cbr202+'" type="text/javascript"></scr' + 'ipt>');
I can't seem to figure out what's causing the issue. Hoping someone with experience can see the problem.
Solved: I figured it out... it was due to my own sloppiness. I should have the jquery event handler below the document.write script, not above it.
You forgot to add a closing } to the function. That caused an error and resulted in any JS coming after that to not execute.
function validateForm() {
var valid = true;
var errMsg = "";
var email = document.emailform.email.value;
var filter = /^([a-zA-Z0-9_.-])+#(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
if(email.length <= 0) {
valid = false;
errMsg += "Email address is required.\n";
} else {
if (!filter.test(email)) {
valid = false;
errMsg += "Please provide a valid email address.\n";
}
}
if (errMsg.length > 0) {
alert(errMsg);
return false;
}
}
the url generated by
src="http://mysite.com/landing.php?lpip=411&202cb='+cbr202
does not exist. The browser tries to load the script from the url using a get request and fails.
cbr202=Math.random()*10000000000000000;
I think you need change code same below
var cbr202=Math.random()*10000000000000000;

Categories