Javascript alert coming up when not expected - javascript

I am trying to ensure that all fields of a form are not empty. When there are empty fields this alert comes up as expected, however when all fields are full the alert still comes up. Am I missing something?
var sn = document.myForm.address.length;
var sna = document.myForm.street.length;
var su = document.myForm.city.length;
var st = document.myForm.state.length;
var usn = document.myForm.username.length;
if (sn || sna || su || st || usn == null) {
alert("All fields are required. Please ensure you leave no fields blank.");
return false;
} else {
}

Since you initialized all your variables, your if statement is evaluating true like this:
if (true || true || true || true || true || false)
Only one true makes the entire if condition above evaluate to true because all the || operators are OR operators.
Consider further, if you simply declare but do not initialize a variable for example var sn; //declared as opposed to var sn = document.myForm.address.length; //initialized then its condition evaluates to false because if(sn) is declared but not initialized = false`.
Moreover, to check the value inside each variable rather than whether or not they are initialized, you must do this:
if (sn == null || sna == null || su == null || st == null || usn == null)
or possibly since you're assigned a length you want this
if (sn > 0 || sna > 0 || su > 0 etc...

Related

Getting uncaught exception in javascript

I am getting "Uncaught SyntaxError: Unexpected token '}" error in browser console and the below message popup is not showing though all conditions are satisfied.
Can someone point out the error here
*
IF (dmd.is_txt(videntifier) = 'TRUE' AND gb = 'S' AND hn AND (vp IS NULL OR vp = '')) THEN
htp.p('<script language = "javascript"> if(ghb != null && eff != "" && ghg != "NULL")
{
var fhh = confirm("223?");
if (answer_preorder)
{
theform.ghb.value = ghy;
</script>');
bsave := true;
htp.p('<script language = "javascript">
}
else
{
theform.ghh.value = ghh;
</script>');
gh := false;
htp.p('<script language = "javascript">
}
}
</script> </script>');
END IF;
*
You cannot split a JavaScript block over multiple script tags; you need to put the entire code into a single script.
You appear to want something like:
IF (
dmd.is_gpid_packaged_txt(videntifier) = 'TRUE'
AND dbcode = 'S'
AND bsave
AND vpreorderdt IS NULL
)
THEN
htp.script(
'if (voldpreorderdate != null && voldpreorderdate != "" && voldpreorderdate != "NULL")'
|| '{'
|| 'var answer_preorder = confirm('
|| '"The preorder is currently live, this will not remove it from Apple.'
|| ' Do you want to proceed?"
|| ');'
|| 'theform.vpreorderdt.value = answer_preorder?vstreetdt:voldpreorderdate;'
|| '}',
'javascript'
);
bsave := FALSE;
END IF;
On the first line, it says dmd.is_gpid_packaged_txt(videntifier) = 'TRUE' but if you want to test if something equals something else, you should use two equal signs, or ==, or three equal signs, or ===, if you want to make sure the types are equal too.

Check if a getElementById is empty

I have a if else function in javascript:
if(document.getElementById('lengthFront').value > 4 && document.getElementById('lengthFront').value < 296 && document.getElementById('lengthBack').value > 4 && document.getElementById('lengthBack').value < 296)
{
document.getElementById('param_length').classList.remove('bg-danger');
}
else
{
document.getElementById('param_length').className = "bg-danger";
}
Bu I need an extra check so it won't be executed when lengthFront or lengthBack is empty, I have tried different solutions but I can't find the right way to get it working. All my solutions are pointing to else
I have tried to add:
document.getElementById('lengthFront') == '' && document.getElementById('lengthBack') == '' &&......
document.getElementById('lengthFront') == false && document.getElementById('lengthBack') == false &&......
document.getElementById('lengthFront') == null && document.getElementById('lengthBack') == null &&......
document.getElementById('lengthFront') =!= undefined && document.getElementById('lengthBack') != undefined &&......
Any suggestions
if(document.getElementById('lengthFront') && document.getElementById('lengthFront').value != '')
First condition makes sure that the element exists, second one makes sure it's value is not empty.
For the most concise and readable approach to dealing with DOM elements that may or may not exist and that may not have a valid value if they do exist, might I suggest you leverage two friends: logical AND && which you can use as a faux null coalescing operator, and the 'conditional ternary' operator ?: in such a way that you can check for null and blank string, and then assign a default value (0) or the element value, all in the initial assignment statement. Also, you'll want to avoid multiple redundant getElementByXXX queries by simply assigning the result to a variable (better readability, less typing, performs faster):
var lengthFront = document.getElementById('lengthFront');
var lengthBack = document.getElementById('lengthBack');
var paramLength = document.getElementById('param_length');
lengthFront = (lengthFront && lengthFront.value != '') ? lengthFront .value : 0 ;
lengthBack = (lengthBack && lengthBack.value != '') ? lengthBack .value : 0 ;
if(lengthFront > 4 && lengthFront < 296 && lengthBack > 4 && lengthBack < 296) {
paramLength && paramLength.classList.remove('bg-danger')
} else {
paramLength && (paramLength.className = "bg-danger");
}

Adding the OR operator to a quizz form makes it accept any answers

I'm having a weird problem when trying to create a question form that is validated with Javascript:
If I write my validation like this:
if (typedValue === "myAnswer" && clearedLevels === 1){doStuff}
Everything works. But I want to create several correct answers, so I write:
if (typedValue === "myAnswer"||"secondAnswer" && clearedLevels === 1){doStuff}
..and all of a sudden anything written to the input form is accepted as the answer.
A correct way of writing it is :
if ((typedValue === "myAnswer" || typedValue === "secondAnswer") && clearedLevels === 1) { doStuff() }
You cannot combine the condition (x === y || x === z) as x === y || z and expect the same results.
Any non-empty string in Javascript is true (yes, even the string "false"). Since "secondAnswer isn't empty, it's evaluated as true, and ORed with any other condition will result in true.
You are missing a comparison of typedValue to this literal, and presumably, brackets around the typedValue comparisons, since && has higher precedence than ||:
if ((typedValue === "myAnswer" || typedValue === "secondAnswer") &&
clearedLevels === 1) {
// doStuff
}
extending Akash Pradhan answer you could write
if (typedValue == "myAnswer" || typedValue == "secondAnswer" && clearedLevels == 1) { doStuff() }
but since the && has precedence over the || operator it would evaluate
if (typedValue == "myAnswer" || (typedValue == "secondAnswer" && clearedLevels == 1)) { doStuff() }

Why is this '=' syntax incorrect in this js snippet?

var hungry = true;
var foodHere = true;
var eat = function() {
if (hungry && foodHere === true) {
return(true);
} else {
return(false);
}`
};
The first line is the correct syntax. For a long time I was just saying hungry && foodHere = true... and I couldn't figure out (and still don't understand) why that is wrong. I understand the difference between = (assignment) and === (equal to). I assigned the variables to be true initially, so aren't I asking in the if statement if that's what they're set to? Why am I setting the variables = to in the var definition, but then when checking them I'm using the === value?
= is only used to assign variables. === or == are used to compare. For a good example, we must look into comparison operators.
Syntax
The syntax of comparison operators is fairly simple, use them to evaluate expressions. The comparasin operators are:
=== //strict equality
== //Parsed or partial equality
> //Greater Than
< //Less than
>= //Greater than or equal to
<= //Less than or equal to
To properly use these, you must know the proper syntax. For example, I can't do something like:
if(true == 1 === true) //do something
as that would invalidate the code, and slow it down by much using ==, which brings me to my next section.
Equality
The two equality operators in JavaScript are == and ===. They do two very different things.
===
The strict equality (===) tests whether two values are exactly equivalent, both in type and value.
==
The Parsed equality (==) tests whether two values are equalivent in value, but parses to try and connect different types.
Inequality
There are 2 main inequality value in JavaScript (!==) they are pretty self explainatory based on the equalities (===, and ==)
here's a chart explaining the three.
1 0 true false null undefined ""
1 === !== == !== !== !== !==
0 !== === !== == == == !==
true == !== === !== !== !== !==
false !== == !== === == == ==
null !== == !== == == == ==
undefined !== == !== == == === !==
"" !== == !== == == !== ===
Adding onto what #jcollum said, = defines a variable value, and if(something === true) simplifies into if(something). Similarly, if(something === false) simplifies into if(!something).
You also need to do comparisons separately. if(7 & 6 < 10) returns false because it is the simplified version of if(7 === true && 6 < 10).
It turns:
hungry && foodHere === true
into
hungry && true
or just
hungry
Using the assignment operator instead of the comparison operator is stopping your logic from working correctly.

How can I break the law of non-contradiction in Javascript?

The law of non-contradiction dictates that two contradictory statements cannot both be true at the same time. That means that the expressions
(a && !a)
(a == !a)
(a === !a)
should always evaluate to a falsy value, and
(a || !a)
should always evaluate to a truthy value.
Fortunately, though, Javascript is a fun language that allows you to do all sorts of sick things. I bet someone a small fortune that it's possible to convince Javascript to break the law of non-contradiction, or, at least, convincingly make it look like it's breaking the law of non-contradiction. Now I'm trying to make all four of the above code examples give the unexpected result.
What would be a good way to go about this?
The best I can do is:
[] == ![] // true
or
var a = [];
a == !a
Of course this is really doing [] == false // true and !![] == ![] // false. It's really just a technicality.
EDIT: This is really a joke, but does work:
var a = false; var b = function() { return a = !a };
console.log(!!(b() && !b())); // true
console.log(b() == !b()); // true
console.log(b() === !b()); // true
console.log(b() || !b()); // true
This one will do the trick:
var a = '0';
a == !a
(evaluates to true)
In this case, a == false and !a == false.
a=NaN;
var a=NaN,
A=[(a && !a), (a == !a),(a === !a),(a || !a)];
alert(A)
/* returned value: (Array)
NaN,false,false,true
*/
I still haven't found anything to break && and ===, but here's one for == and ||:
Object.prototype.toString = function() {
return false;
};
a = {};
b = (a || !a);
alert(a || !a); //alerts false
alert(b == !b); //alerts true

Categories

Resources