If/Else validation not working like it should - javascript

I am trying to get this validation to work and I am having some difficulties. This is the code that I have:
function validateCarsMinMax(v) {
if (tfRateLoc1.getValue() > '0' && tfRateLoc2.getValue() > '0') {
if (tfRateLoc3.getValue() != '0') {
return '1B cannot contain a value if CW is entered';
}
} else return true
}
It seems to not like the && tfRateLoc2.getValue() > '0' line because it works just fine when I take it out. Any suggestions?

I am assuming that getValue() returns a number and '0' is a string not a number so the comparison incorrect.
if (tfRateLoc1.getValue() > 0 && tfRateLoc2.getValue() > 0) {
if (tfRateLoc3.getValue() != 0) {
Other issue is you never return a value if if (tfRateLoc3.getValue() != '0') { is false

This worked for me:
function validateCarsMinMax(v){
if (tfRateLoc1.getValue() > 0 || tfRateLoc2.getValue() > 0){
if (tfRateLoc3.getValue() > 0){
return '1B cannot contain a value if CW is entered';
}
} else return true
}

if (parseInt(tfRateLoc1.getValue()) > 0 && parseInt(tfRateLoc2.getValue()) > 0
&& parseInt(tfRateLoc3.getValue()) != 0)
{
return '1B cannot contain a value if CW is entered';
}else return true

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.

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.

jquery if else doesnt give back an alert message

everything is writen in an external javascript file what I included in the html I also have the jquery link in there.
I tried to change put the if statment on diffrent positions in the code, I looked arround if the width was incorrect and some other things whitch are inrelevent at the moment.
When I changed the $foodcheck).width > '0px' to a < and the else if to a > the alert did work but ofc I only want it to pop up if the width = 0
I want it to give back the alert message.
var $foodcheck = $('#greenfood');
if(($foodcheck).width > '0px') {
document.getElementById("f").onclick = function(){
var random = Math.random();
if(random > 0.0 && random <= 0.5) {
$("#greenfood").animate({width: "-=30px"});
} else if(random > 0.9) {
$("#greenfood").animate({width: "-=80px"});
} else {
$("#greenfood").animate({width: "140px"});
}
};
} else if(($foodcheck).width =< '0px'){
alert("Works");
}
You have quite a few problems with your code.
First of all, ">" and "<" should be done with numbers. Therefore the code >"0px" makes NO sense in this context, as you are really comparing the dictionary order of the characters in ASCII. Not the value of the integers.
i.e.
"a" < "b" //true as 'a' < 'b' => 97 > 98 (converted to ASCII numbers)
"ab" < "ac" // true as 'a' == 'a' and 'b' < 'c'
"ab" < "ac" // true as 'a' == 'a' and 'b' < 'c'
"5px" > "11px" //true as '5' > '1'
What you should have done is compared the value like so:
5 > 11 //false as 5 < 11
Here is your corrected code:
var $foodcheck = $('#greenfood');
if($foodcheck.width() > 0) { // CHANGE: Additional Brackets were not needed. width should be width()
$("#f").click(function() { //This is the jquery way of doing events although your way also works
var random = Math.random();
if (random > 0.0 && random <= 0.5) {
$foodcheck.animate({width: "-=30px"}); //IMPROVEMENT: used stored variable instead of finding the object again.
} else if(random > 0.9) {
$foodcheck.animate({width: "-=80px"});
} else {
$foodcheck.animate({width: "140px"});
}
});
} else if ($foodcheck.width() =< 0){
alert("Works");
}
jQuery's width() returns the computed width in pixels so you need to update you script to call it correctly. (note, its a function so needs the parenthesis).
Here's a working example:
$(function(){
var $foodcheck = $('#greenfood');
if($foodcheck.width() > 0) {
document.getElementById("f").onclick = function(){
var random = Math.random();
if(random > 0.0 && random <= 0.5) {
$foodcheck.animate({width: "-=30px"});
} else if(random > 0.9) {
$foodcheck.animate({width: "-=80px"});
} else {
$foodcheck.animate({width: "140px"});
}
}
} else {
alert("$foodcheck is <= 0 or undefined");
}
});
#greenfood {background:green; width:200px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="greenfood">greenfood</div>
<button id="f">click</button>
UPDATE:
From your comments it's apparent that you want to check the width every time. Simply move the width checking clause inside the onclick event:
$(function(){
var $foodcheck = $('#greenfood');
document.getElementById("f").onclick = function(){
var random = Math.random();
if($foodcheck.width() > 0) {
if(random > 0.0 && random <= 0.5) {
$foodcheck.animate({width: "-=30px"});
} else if(random > 0.9) {
$foodcheck.animate({width: "-=80px"});
} else {
$foodcheck.animate({width: "140px"});
}
} else {
alert("$foodcheck is <= 0");
}
}
});
#greenfood {background:green; width:200px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="greenfood">greenfood</div>
<button id="f">click</button>
I think you're doing it wrong at this line:
($foodcheck).width > '0px')
It should be
($foodcheck).width > 0)
And this line:
else if(($foodcheck).width =< '0px')
Should be:
else if(($foodcheck).width =< 0)
else if(($foodcheck).width =< '0px'){
this code throw error "<=" not "=<" if everything with the html is ok and you have element with id="f" this will fix it !
also $foodcheck).width must be $foodcheck).width() <= 0 number not string like your example

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.

Looping through javascript function

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;
}
}

Categories