Looping through javascript function - javascript

I'm trying to loop my if statements inside a while loop through my function. But it will only hit the first if statement and stop looping.
Sample:
while(No.length == 0 || Name.length == 0 || Tel.length == 0
|| Date.length == 0 || Email.length == 0) {
alert("Don't leave blank!");
if (No.length == 0) {
document.getElementById('Nos').style.visibility = 'visible';
return false;
}
if(Name.length == 0) {
document.getElementById('Name').style.visibility = 'visible';
return false;
}
//continues same if statement for rest of the elements variables.
}
It will only go to the first if statement and will not loop through it.

You are returning from inside the loop; that breaks the loop. If you want to continue on to the next round of the loop, use continue instead. If you want to break out of the loop, but not return from the entire function, use break.
Now if you are using a jQuery loop, because it's really just a function, you do use return:
$.each([1,2,3,4], function(index, x) {
if (x < 4) return true; // equivalent to continue
if (x == 4) return false; // equivalent to break
});
but that's only for jQuery loops, not Javascript standard ones.

The first error I can see is you should escape your alert with '\' for example :
alert('Don\'t leave blank!');
And the loop with just continue if you write this :
while(No.length == 0 || Name.length == 0 || Tel.length == 0 || Date.length == 0 || Email.length == 0) {
if (No.length == 0) {
document.getElementById('Nos').style.visibility = 'visible';
}
if(Name.length == 0) {
document.getElementById('Name').style.visibility = 'visible';
}
return true;
}
Could also try:
while(No.length == 0 && Name.length == 0 && Tel.length == 0 && Date.length == 0 && Email.length == 0) {
document.getElementById('Nos').style.visibility = 'visible';
document.getElementById('Name').style.visibility = 'visible';
continue;
}

Maybe this?
function test_all_fields() {
var No = document.getElementById('No');
var Nos = document.getElementById('Nos');
var Name = document.getElementById('Name');
// ...
Nos.style.visibility = (No.value.length==0) ? 'visible':'hidden';
Names.style.visibility = (Name.value.length==0) ? 'visible':'hidden';
//...
//continues same if statement for rest of the elements variables.
if (No.value.length >0 && Name.value.length >0 && Tel.value.length>0 && Date.value.length >0 && Email.value.length>0) {
return true;
}
else {
alert("Don\'t leave blank!");
return false;
}
}

Related

How do I check nested If statements in JavaScipt

I'm new to JavaScript, so I'm currently working on a script that is supposed to update a string called Wasl_Status. These are the for conditions I'm trying to check:
Here is my code so far:
if (analog2 == 0) {
return "Tamper Weight";
}
if ((analog1 == 0) && (speed == 0)) {
return "Parked Device Disconnected";
}
if ((analog1 == 0) && (speed > 0)) {
return "Moving Device Disconnected";
if ((ignition == true) && (speed == 0))
return 'Parked Engine On';
if ((ignition == false) && (speed == 0))
return 'Parked Engine Off';
if (speed > 0)
return "Moving";
}
When I test it, the Wasl_Status only outputs the first three conditions and it ignores all the last three conditions. How do I make it to check every condition and return all 6 values? What I read so far is to create an array but current instructions say I must do nested if statements. I hope my question is clear. Thank you.
While it's correct, what you're doing, I think it's easier to read and follow the code if you, in most cases, try to return the value at the end of the function:
var message = 'no statements fit';
if (analog2 == 0) { message = "Tamper Weight"; }
else if (analog1 == 0 && speed == 0) { message = "Parked Device Disconnected"; }
else if (analog1 == 0 && speed > 0) {
message = "Moving Device Disconnected";
if (ignition == true && speed == 0) { message = 'Parked Engine On'; }
else if (ignition == false && speed == 0) { message = 'Parked Engine Off'; }
else if (speed > 0) { message = "Moving"; }
}
return message;
Then you would see, in an easier way, what is returning and when:
if ((analog1 == 0) && (speed > 0)) {
return "Moving Device Disconnected";
// ... everything after this code will never be executed because the function "stops" executing after a return.

loop won't go through first if statement

My code will only go through to the first if statement where it checks the value of key for headline1 etc... The first if statement works properly but it won't work with any of the following if statements when the first one isn't true. I've switched the second statement to the first where it checks for 'desc1' and then it works for that one only.
The purpose of this function is to check each key of an object and return the key when its value is over a certain length so I can add a class and show user some warning. This is in Vue JS so ads is in data and characterCheck is in computed property.
ads: [
{
headline1: '_keyword_',
headline2: 'Online',
headline3: 'Free',
desc1: 'Buy online _keyword_',
desc2: ' Vast collection of _keyword_',
finalurl: 'www.books.com',
path1: '',
path2: '',
boolean: true
}
]
characterCheck () {
for(var x = 0; x < this.ads.length; x++){
if(this.ads[x]['boolean'] == true) {
for(var key in this.ads[x]){
var length = this.ads[x][key].replace(/_keyword_/g, this.activeKeyword).length
if( key === 'headline1' || key === 'headline2' || key === 'headline3'){
if(length > 30){
return key
}
} else if( key == 'desc1' || key == 'desc2'){
if(length > 90){
return key
}
} else if( key == 'path1' || key == 'path2'){
if(length > 15){
return key
}
} else {
return false
}
}
}
}
}
When your first nested if condition fails, the code goes to next subsequent else-if. For some particular value, all the if and else-if block fails and code lands on final else block which contains a return statement.
If your code reaches even once there, the entire function execution immediately stops and false value is returned.
Since, you wish to wait as long as you have not looped through all the values, remove the else part and add a simple return statement to the end of the for loop like this:
function characterCheck () {
for(var x = 0; x < this.ads.length; x++) {
if(this.ads[x]['boolean'] == true) {
for(var key in this.ads[x]) {
var length = this.ads[x][key].replace(/_keyword_/g, this.activeKeyword).length
if( key === 'headline1' || key === 'headline2' || key === 'headline3') {
if(length > 30) {
return key
}
}
else if( key == 'desc1' || key == 'desc2') {
if(length > 90) {
return key
}
} else if( key == 'path1' || key == 'path2') {
if(length > 15) {
return key
}
}
}
}
}
return false
}

else if statement getting ignored

I have a function that has to act different if pan.cost > 0.
So let's say curPos = 3 and pan.cost = -1
Now when I do this, no matter what, if(curPos + 1 === 5 || 30) is always used even if curPos + 1 is 2,3,4,6 etc (as long pan.cost < 0)
Now I have put console.log(curPos + 1) inside the else if-statement and it also says their that it does not meet the requirements.
function action(curPos)
{
var pan = panel[curPos];
if(pan.cost > 0)
{
}
else if(curPos + 1 === 5 || 39)
{
console.log(curPos + 1);
}
else if(curPos + 1 === 3)
{
console.log("should be here");
}
}
Try this:
function action(curPos)
{
var pan = panel[curPos];
var newCurPos = (curPost + 1);
if(pan.cost > 0)
{
}
else if(newCurPos === 5 || newCurPos === 39)
{
console.log(newCurPos);
}
else if(newCurPos === 3)
{
console.log("should be here");
}
}
The line
curPos + 1 === 5 || 39
always evaluates to truthy, because it is read:
(curPos + 1 === 5) || 39
and 39 is a truthy value.
if(curPos + 1 === 5 || 39) will always evaluate to true. Look at the part after your or pipes. if(39) will always be true.
|| 39 will always return true and pan.cost doesn't exist.

Validating numeric values using JavaScript

I have the following code. It works fine for blank fields, but it doesn't catch the other numeric exceptions. What am I doing wrong?
function validateForm() {
var a = document.forms["Form"]["percentage"].value;
var b = document.forms["Form"]["minutes"].value;
if (a == null || b == null || a == "" || b == "") {
alert("Please Fill All Required Field");
return false;
} else if (isNan(a) == true || isNan(b) == true) {
alert("Please enter valid numeric values");
return false;
} else if (parseInt(a) > 100) {
alert("Percentage can't exceed 100");
return false;
} else if (parseInt(b) < 0 || parseInt(a) < 0) {
alert("Values can't be negative");
return false;
}
}
Change this line:
else if((isNan(a)==true) ||(isNan(b)==true)){
to this:
else if (isNaN(a) || isNaN(b)) {
as the function is named #isNaN(). Using == true in conditionals is quite redundant, so I removed them.
I have also made a fiddle for you. It contains the fixed code, and it is working well.

Appending conditions in a numerical loop (JavaScript)

I have four IF statements, is it possible to rewrite this into a neater loop, where the [i] may be '4' or higher.
if (typed.length == 1 && c.charAt(0) == typed[0]) {
//something ;
return false;
}
if (typed.length == 2 && c.charAt(0) == typed[0]
&& c.charAt(1) == typed[1]) {
//something ;
return false;
}
if (typed.length == 3 && c.charAt(0) == typed[0]
&& c.charAt(1) == typed[1] && c.charAt(2) == typed[2]) {
//something ;
return false;
}
if (typed.length == 4 && c.charAt(0) == typed[0]
&& c.charAt(1) == typed[1] && c.charAt(2) == typed[2]
&& c.charAt(3) == typed[3]) {
//something ;
return false;
}
Looks to me like something like this should to it:
if (c.substr(0, typed.length) == typed)
Possibly typed.join() if typed is an array.
Try this
for(var x=0; x<typed.length; x++)
{
if(c.chatAt(x)!=typed[x]) { return false; }
}
return true;
for (var i=1; i<=4; ++i){
if (typed.length!=i) continue;
var OK = true;
for (var j=0;j<i;++j){
OK = OK && (c.charAt(0)==typed[j]);
}
if (OK){
// something
return false;
}
}
Forget about two nested loops, or assuming c and typed are "ordered", just look for the char in c
for (var i=0; i<typed.length; i++) {
if (c.indexOf(typed.charAt(i)) >= 0) { // or c.indexOf(typed.charAt(i)) == i
return false;
}
}
return true;

Categories