jquery check variable values - javascript

In jQuery I have the following 4 variables.
var add
var city
var state
var zip
I need to check to see that any one of the above have a value.
If none have a value that is OK. If all of them have a value that is OK.
Just need to check that at least one of them do not have a value.
Not sure what is the most efficient way of doing this.

var check = [ add, city, state, zip ].every( function ( v ) { return !!v } )
Just for the sake of showing off.
Explaination: the every method loops through all the array and returns false if one of the conditions returns false and stops immediately the loop. If all the loops return true, true is returned.
PS: v is for "variable".

var check = (function(a, b, c, d) {
return !!a && !!b && !!c && !!d;
}(add, city, state, zip));
console.log(check);
another method... lets learn some new techniques today!
this will actually check to see if the value is not false. anything else is ok (strings, numerics, TRUE).

Simply
if (yourVar)
{
// if yourVar has value then true other wise false.
}
Hope thats what you required..

to check i a variable has a value assign it to it you can do:
var myVar
....
if (typeof myVar === 'undefined'){
// here goes your code if the variable doesn't have a value
}

if(!add || !city || !state || !zip) {
console.log('exists var with no value');
}

if( add.length == 0 || zip.length == 0 || city.length == 0 || state.length == 0) {
alert("at least one of the variables has no value");
}; else if (add.length == 0 & zip.length == 0 & city.length == 0 & state.length == 0) {
alert("all of the variables are empty");
}; else { alert("okay"); }

Related

if statement with more than one condition

I need to check three conditions,
sheet_exists = 1
recalc = 1
qty_total and new_qty_total are not equal
The if statement works well if only the first 2 arguments are used:
if(sheet_exists === 1 && recalc === 'yes'){
//do something
}
But when I try to add he 3rd argument it fails, the actions in the if statement are ignored. I've tried:
if((sheet_exists === 1) && (recalc === 'yes') && (qty_total !== new_qty_total)){
//do something
}
And:
if(sheet_exists === 1 && recalc === 'yes' && (qty_total !== new_qty_total)){
//do something
}
And:
if(sheet_exists === 1 && recalc === 'yes' && qty_total !== new_qty_total){
//do something
}
Where am I going wrong?
Considering you are happy with the behavior of the first two conditions, and not with the last one, the problem must be in the last one.
Pay attention, qty_total !== new_qty_total will return TRUE only when the value or type of qty_total and new_qty_total are different.
If one is an integer 100 and the other is a string '100' then the condition evaluates as TRUE because they differ on the data type. But if they are both integers it will return FALSE, because neither the value nor the type are different.
To make sure the comparison works ok, make sure both variables are the same data type.

Javascript dynamic conditioning

I want to build a IF condition which is built dynamically based on the parameters it gets. More over, this is expected to be built as a plugin.
For instance, there are 3 parameters for student object, called age,name, phone_numbers. Also, there is a option object for selection parameters.
In the condition,
if(student.age >option.age & student.name == option.name & student.phonenumbers == option.phonenumbers ){
// do stuff
}
If any parameter is missing, it should not be included in the condition. For example, assume, in case option.name is undefined, then the if condition should be prepared as following,
if(student.age >option.age & student.phonenumbers == option.phonenumbers ){
// do stuff
}
Moreover, why this kind of thing is required is, here an array of (500 objects) students objects are iterated. The above condition can be splitted into seperat conditions, but then the iteration will be multipled by the number of conditions !!!. So I m looking for a way to add all conditions into one.
However, my approach is, create the expression as a string and then execute it with eval(..),but as far as I know that using eval can lead vulnerabilities.
Any one let me know a way to implement a dynamic conditions.
Note that the JavaScript and operator is &&.
For your example, this should work:
if((!student.age || student.age>option.age) &&
(!student.name || student.name==option.name) &&
(!student.phonenumbers || student.phonenumbers==option.phonenumbers)
) {
}
How about
function testStudent(student,option) {
var res = [];
var test = true;
if (student.age) res.push(student.age > option.age);
if (student.name) res.push(student.name == option.name);
if (student.phonenumbers) res.push(student.phonenumbers == option.phonenumbers);
for (var i=0;i<res.length;i++) {
test = test && res[i];
}
if (res.length > 0 && test) {
//do stuff
}
}
generic:
function testObjects(obj1,obj2) {
for (var o in obj1) { // assuming obj2 is a superset of obj1
if (o === "age" && obj1.age <= obj2.age) return false;
if (obj1.hasOwnProperty(o) && obj1[o] != obj2[o]) return false;
}
return true;
}
var ok = testObjects(student,option);
You can have your conditions in functions and those functions in an Array. so then you can do a loop in the Array and call every function (condition).
var aConds = [];
function firstCond(params) {return (params<0)};
function secondCond(params) {return(params!='hi')};
aConds.push(firstCond);
...
for(var i=0;i<aConds.length;i++)
{
if(!aConds[i](params)) console.log("a condition has not been meet");
}
Would it work to allow undefined in each condition?
if((student.age == undefined || student.age > option.age) && (student.name == undefined || student.name == option.name) ...

checking values before submitting form

Before I submit a form I want to check the values in the input.
Here I'm checking if a value is NOt equal to .5 or 1. or not a empty string.
form.onsubmit = function(e) {
var ftimes = document.getElementsByClassName("add_timebox");
var fflag = 0;
for(i=0;i< ftimes.length;i++) {
var value1 = ftimes[i].value;
console.log(value1);
if ( value1 !==.5 ||value1 !== 1 || (!IsStringEmpty(value1)) ){
fflag = 1;
console.log('inside');
}
}
if(fflag==1) {
alert('enter again' );
return false;
}
I have made many changes to the IF statement to try to get it correct.
But it is still going in the loop even when I know if shouldn't.
For example when i submit the form and i have one input value equal .22
then it should only give me 1 'inside' but in keeps repeating:
inside
.22
(empty string)
inside
....
You do not show how you are implementing your IsStringEmpty method, but if you are using something like this, then any number is also a non-empty string, so your if statement will always run.
function IsStringEmpty(str) {
return (!str || 0 === str.length);
}
So you need to change your ORs with ANDs, or it will never check the number conditions.
You can check if the value is not an empty string and is different from 0.5 and 1. Then your condition should be like this.
if (!IsStringEmpty(value1) && value1 !== 0.5 && value1 !== 1)
But, you are getting the value from a form, so it will be a string. Therefore, you are comparing strings and you need this.
if (!IsStringEmpty(value1) && value1 !== ".5" && value1 !== "1")
Although you will probably want to compare floats, in which case you need this.
if (!IsStringEmpty(value1) && parseFloat(value1) !== .5 && parseFloat(value1) !== 1))
So basically, when you enter 1, .5 or and empty string in all of the form fields, you skip the inside block. But if you have any other value in any of the fields, then the flag will be set to 1. If that is not what you meant, please update your question to be more specific.
Please check Plunker here.
Hope this helps.
you have to add a break; statment in your if condition once the if condition is satisfied.
if ( value1 !==.5 ||value1 !== 1 || (!IsStringEmpty(value1)) ){
fflag = 1;
console.log('inside');
break;
}

Is there any way of determining which or statement is true in javascript?

So say I have an if statement:
if(a=='' || b==''){
//which is true?
}
Is it possible to determine which statement satisfied the if statement without doing a switch statement or another if statement to check?
You can define a token to store what condition was true:
var token = null;
if ((a == '' && (token = 'a')) || (b == '' && (token = 'b'))) {
// Here token has an 'a' or a 'b'. You can use numbers instead of letters
}
I think it's the simplest way to do what you want.
As others have said, you have to test the conditions separately, but you can kind of mix worlds.
var test1 = 1 == 1; // true
var test2 = 2 == 1; // false
if (test1 || test2) {
// If either conditions is true, we end up here.
// Do the common stuff
if (test1) {
// Handle test1 true
}
if (test2) {
// Handle test2 true
}
}
No, you have asked explicitly if one or both are true. There's no way to work out which of those sub-expressions is true without another conditional of some sort.
If you're interested in different behaviour based on which is true, you should probably separate them with a possibly-common bit, something like
either = false;
if (a == ' ') {
doActionsForA();
either = true;
}
if (b == ' ') {
doActionsForB();
either = true;
}
if (either) {
doActionsForAorB();
}
If you care about which of the two conditions is true the only way to find out is to test them separately, e.g.
if(a==''){
// ...
}
else if(b=='') {
// ...
}
Sometimes, especially in more complicated conditionals, it helps if you store the result of each condition and reuse it later on:
var isFoo = a == '';
var isBar = b == '';
// You can now use isFoo and isBar whenever it's convenient
the simple solution:
if ((ia=(a=='')) || (b=='')) {
// ia indicate whether the boolean expression a have been true.
// ia -> a has been true, b may have, !ia -> b has been true, a has not
}
there is no ib in the simple solution as it won't be always be set due to shortcut evaluation.
to cater for shortcut evaluation try:
if (((ia=(a=='') || (ib=(b=='')) && ((ib=(b=='')) || (ia=(a==''))) {
// ia, ib indicate whether the corresponding boolean expressions have been true
}
if(a=='' || b==''){
var x= a || b;
//if a is ''(falsy) x will be b, else a
}
var phone="";
var email="something";
if(phone=='' || email==''){
var x= (phone) ? 'phone':'email';
console.log(x); //email
}

Meaning of == "" in javascript

Short questioion, I'm trying to understand this tutorial:
http://superdit.com/2011/02/09/jquery-memory-game/
Being new to Javascript I can't seem to find what the statement '== ""' means... I understand "==", but not the empty double quotes.
val == "" is a non-strict comparison to emtpy string. It will evaluate to true if val is empty, 0, false or [] (empty array):
var val = "";
console.log( val == "" ); // true
val = 0;
console.log( val == "" ); // true
val = false;
console.log( val == "" ); // true
val = [];
console.log( val == "" ); // true
You can use === to use strict comparison, fex:
val = 0;
console.log( val === "" ); // false
The ' == "" ' is a check for an empty string. It will be true when the string is empty, and false whenever there are some characters inside it.
A quick scan of the code (ctrl-F is your friend) quickly teaches you that the only time such a statement occurs in the code is here: if (imgopened == ""), another search taught me that imgopened is an evil (global) variable that is initialized to "" at the very top of the script, and every time some action/function is done with whatever value it was assigned.
I suspect it's a sort of card game, where two identical imgs need to be clicked, in which case this var will reference the image currently turned. If it's empty, then all imgs are facing down, and this var is empty: "".In other words:
if (imgopened == "")//=== if no card is turned
{
//do X, most likely: turn card
}
else
{
//do Y
}
This could've been written as
if (!imgopened)
//or
if (imgopened == false)//falsy, but somewhat confusing
//or
if (imgopened == 0)//!confusing, don't use
//or, my personal favorite
if (imgopened === '')

Categories

Resources