I am facing an issue in javascript. if key value is true they stop it return true whereas if key value is false they shows Error.
Problem: they don't read the condition number or name value in if body. if key value is true they terminate.
How should i handle this condition? that they should also read the condition number or name value in if body.
can i use else if statement here ?
var key = $('#key').val().trim();
if(key != "" ){
return true; //value is true if value is true they stopped it
}
if(key === ''){
showError(); //this field is required
return false;
}
//if key value is true they don't execute my number or name condition
if ( $('#number').val().trim() === '' || $('#name').val().trim() === '' )
{
if ($('#number').val().trim() === '') {
showError(); //this field is required
}
if ($('#name').val().trim() === '') {
showError(); //this field is required
}
return false;
}
else{
return true; //always return true
}
how can i do? anyone help me?
Not sure if this is what you wanted. Have a look. The code continues after checking key.
var key = $('#key').val().trim();
if(key === ''){
showError(); //this field is required
let keyStat = false;
}
//if key value is true they don't execute my number or name condition
if ( $('#number').val().trim() === '' || $('#name').val().trim() === '' || keyStat === false) {
if ($('#number').val().trim() === '') {
showError(); //this field is required
}
if ($('#name').val().trim() === '') {
showError(); //this field is required
}
if (!keyStat) {
showError(); //this field is required
}
return false;
}
else{
return true; //always return true
}
when you call return statement your function will exit,only code before the return statement will run
Example:
function bar(){
var key = 12
if(key === 12){
console.log("only code before the return statement will run")
return true; // when you call return your function will exit
}
console.log("this will be terminated")
}
click me
Related
I have function below. It does what it needs to except that it does not return the error string I want.
It always returns "".
I've put breakpoints and seen it step into each error case, but it doesn't return there. It returns at the end of the function.
I'm lost, I'm sure I'm making a really stupid mistake but I don't get it...
Save me the few hairs I have please :)
public validatePanel = () => {
this.Queries().forEach(function(q, i) {
if(q.from() == "" || q.from() == null || q.from() == undefined) {
return "Please select a database";
}
if(q.select().length > 0) {
q.select().forEach(function(s, j) {
if(s.selectoption() == "" || s.selectoption() == null || s.selectoption() == undefined){
return "Please select a stat to show";
}
});
}
if(q.where().length > 0) {
q.where().forEach(function(w, j) {
if(w.whereoption() == "" || w.whereoption() == null || w.whereoption() == undefined){
return "Please select a filter to filter on";
}
if(w.wherevalue() == "" || w.wherevalue() == null || w.wherevalue() == undefined) {
return "Please select a value for your filter";
}
});
}
});
return "";
}
As pointed out by Alex Bykov, your forEach function is not causing a return.
Your question on why not, per the MDN
The return value of the function is undefined
Return
value undefined.
Which means nothing you can do will generate a return value you can use. Also per the MDN there is no way to stop or break the loop other than throwing an exception.
There is no way to stop or break a forEach() loop other than by
throwing an exception. If you need such behavior, the forEach() method
is the wrong tool, use a plain loop instead. If you are testing the
array elements for a predicate and need a Boolean return value, you
can use every() or some() instead. If available, the new methods
find() or findIndex() can be used for early termination upon true
predicates as well.
Which means you will need to throw your exception in the forEach loop and then catch the exception and return the string like below
(unless you use a normal for loop then you can do whatever you please)
try {
this.Queries().forEach(function(q, i) {
if(q.from() == "" || q.from() == null || q.from() == undefined) {
throw "Please select a database";
}
if(q.select().length > 0) {
q.select().forEach(function(s, j) {
if(s.selectoption() == "" || s.selectoption() == null || s.selectoption() == undefined){
throw "Please select a stat to show";
}
});
}
if(q.where().length > 0) {
q.where().forEach(function(w, j) {
if(w.whereoption() == "" || w.whereoption() == null || w.whereoption() == undefined){
throw "Please select a filter to filter on";
}
if(w.wherevalue() == "" || w.wherevalue() == null || w.wherevalue() == undefined) {
throw "Please select a value for your filter";
}
});
}
});
}
catch(err) {
console.log(error);
}
the below is the script i have written, by using below code i am getting error message properly but, if i enter the field the error message still be displaying any idea how to clear the error message.
var flag=0
function otpValidate()
(
otp=oneTimePass.onetimepass.value
if(otp=="")
(
document.getElementById('error0').innerHTML="Enter one time password"
flag=1;
)else if(otp.length != 6)
(
document.getElementById('error0').innerHTML="PIN must be 6 digits"
flag=1
)
)
function check(form)
(
flag==0
otpValidate()
if(flag=1)
return false
else
return true
)
You have many errors.
if(flag=1) is not a condition but an allocation. Write if(flag==1) instead.
Replace function otpValidate() (... ) to function otpValidate() {... }.
It's the same for if statement. Replace if() (...) by if() {...}
Note : At the end line you should add ; in javascript
Code without mistake :
var flag = 0;
function otpValidate() {
otp = oneTimePass.onetimepass.value;
if(otp == "") {
document.getElementById('error0').innerHTML = "Enter one time password";
flag = 1;
} else if(otp.length != 6) {
document.getElementById('error0').innerHTML = "PIN must be 6 digits";
flag = 1;
}
}
function check(form) {
flag = 0;
otpValidate();
if (flag == 1)
return false;
else
return true;
}
Iam using following lines of code to check whether the JS variable 'userName' is null or not.
But am always getting alert "not empty"
Please check my onready method:
$("document").ready(function (){
var userName = "";
if (userName == undefined || userName == null) {
alert('empty');
} else {
alert('not empty');
var div = document.getElementById('title b');
div.innerHTML = div.innerHTML + ',';
}
});
You need typeof keyword to check it's type. !userName will take care of the rest, like null or empty values.
if ( typeof userName === 'undefined' || !userName ) {
alert('empty');
}
You're setting var userName to "". It will never be null.
Declare your variable as var userName;, instead of var userName = "";
However, unless you actually do something with userName, the if / else will be pretty pointless.
No your variable is neither undefined nor null.
What you could do though is this replace this line
if (userName == undefined || userName == null) {
by this line
if (!userName) {
Empty string is not null nor undefined.
You can check using the ! operator:
if (!userName) {
// Do the stuff
}
For completeness:
!"" == true
!null == true
!undefined == true
!"hi" == false
Note that:
!0 == true
!1 == false
!"0" == false
!"1" == false
Try
var userName = "";
if (userName.length < 1) {
alert('empty' +"\n"+ userName.length);
} else {
alert('not empty');
var div = document.getElementById('title b');
div.innerHTML = div.innerHTML + ',';
}
I cannot get my code to work. The second if statement is not being read at all for some reason.
function validateStation(v){
// search store for value... if you find it then true, else false
if (storeStation.findExact('disp',v) > -1) return true;
else return 'This value is not valid.';
if (cbStationFSAC.isValid()) return true;
else return 'This value is not valid.';
}
The function rightfully exits the code after reading the first if/else statement.
Instead try rewriting the code as such
function validateStation(v){
// search store for value... if you find it then true, else false
if (((storeStation.findExact('disp',v) > -1) || (cbStationFSAC.isValid()))
return true;
else
return 'This value is not valid.';
}
You can do something like this so it executes all the condition before returning the value
function validateStation(v){
var output = true;
if (storeStation.findExact('disp',v) > -1)
output = true;
else
output = 'This value is not valid.';
if (cbStationFSAC.isValid())
output = true;
else
output ='This value is not valid.';
return output;
}
The following script should validate only certain input fields depending on the selection a user makes in a drop-down box (var problem).
The trouble I'm having is when the if statement runs for problem == 4 (below) and the user has filled in the corresponding cityid field, the alert (Alert#3) for the next if statement (problem == 5) is triggered. I only want Alert#3 to trigger if the user has selected problem == 5 from the drop-down AND has not filled in the model field.
The same trouble happens respectively when if statement runs for problem == 5.
function ValidateSOR()
{
var user = document.SOR.User;
var problem= document.SOR.Problem;
var cityid = document.SOR.CityID;
var errors1 = document.SOR.ErrorCodes1;
var model = document.SOR.Model;
var errors2 = document.SOR.ErrorCodes2;
var software = document.SOR.SoftwareType;
if (user.value == "")
{
window.alert("Please enter your name.");
user.focus();
return false;
}
if (problem.selectedIndex < 1)
{
alert("Alert#1");
problem.focus();
return false;
}
if (problem.selectedIndex == 4)
{
cityid.focus();
}
else if (cityid.value == "")
{
alert("Alert#2");
cityid.focus();
return false;
}
if (problem.selectedIndex == 5)
{
model.focus();
}
else if (model.value == "")
{
alert("Alert#3");
model.focus();
return false;
}
if (problem.selectedIndex == 6)
{
software.focus();
}
else if (software.value == "")
{
alert("Alert#4");
software.focus();
return false;
}
return true;
}
You're not returning from the function when you discover that the problem is #4. Thus, because it is 4, then it's not 5, and so the "else" part of that branch is taken.
edit — OK, let's look at the code:
if (problem.selectedIndex == 4) {
cityid.focus();
}
else if (cityid.value == "") {
alert("Alert#2");
cityid.focus();
return false;
}
if (problem.selectedIndex == 5) {
model.focus();
}
else if (model.value == "") {
alert("Alert#3");
model.focus();
return false;
}
If the index is 4, what happens? This code runs:
cityid.focus();
Then what? The code proceeds to the next if statement:
if (problem.selectedIndex == 5) {
Now, if we just got through noticing that the index was 4, then what are the chances that it will be equal to 5? Zero! Thus, that comparison is guaranteed to be false, so we move to the else part. Apparently, your "model.value" is the empty string, so that if statement succeeds. You get the alert.
I think your problems would be solved by bringing the logic of the code more in line with the logic of your validation process:
if (problem.selectedIndex == 4 || cityid.value == "") {
cityid.focus();
return false;
}
That way, if the index is 4 or if the city ID value is empty, then you'll treat that as an error with the city ID and exit the function. It won't matter what comes after that, because the return leaves the function at that point.
You should restructure each IF like so:
if (problem.selectedIndex == 4 || cityid.value == "")
{
cityid.focus();
return false;
}
if (problem.selectedIndex == 5 || model.value == "")
//and so on
so it returns either way and does not hit the next if statement