My displayError() function is not working at all - javascript

I made a function that should display an error or remove an error.
Unfortunately, when I use the function in any way, for example like displayError(true, "test");, it's not working.
When I check my html code to see if anything changes, nothing is changed.
function displayError(display, string, xhr) {
$("div#error").fadeOut(300, function() {
if(arguments.length == 1 && typeof display === "boolean" && display == false) {
//do nothing
} else if(arguments.length == 2 && typeof display === "boolean" && display == true && typeof string == "string") {
$("div#error").html('<b style="color: #ce1919;">(!)</b> '+string).fadeIn(300);
} else if(arguments.length == 3 && typeof display === "boolean" && display == true && typeof string == "string" && typeof xhr === "object") {
$("div#error").html('<b style="color: #ce1919;">('+xhr.status+")</b> "+string).fadeIn(300);
}
});
}
Anybody who can identify the problems?

use typeof:
typeof display === "boolean"
typeof xhr === "object"
MDN typeof Reference

I found out about the console log method. So I tried to check if my function was fired at all and it was. But then I found that the arguments array was just empty, which meant that the parameters were not available in the callback. So I stored the arguments in a variable and then used that variable in my if statements in the callback.
Like so:
function displayError(display, string, xhr) {
var args = arguments;
$("div#error").fadeOut(300, function() {
if(args.length == 1 && typeof display === "boolean" && display == false) {
//do nothing
} else if(args.length == 2 && typeof display === "boolean" && display == true && typeof string == "string") {
$("div#error").html('<b style="color: #ce1919;">(!)</b> '+string).fadeIn(300);
} else if(args.length == 3 && typeof display === "boolean" && display == true && typeof string == "string" && typeof xhr === "object") {
$("div#error").html('<b style="color: #ce1919;">('+xhr.status+")</b> "+string).fadeIn(300);
}
});
}

Related

Javascript needs to prevent blanks from being entered

The following Javascript is attached to a field form (on change ) it is supposed to ensure that if the user clicks on a button then 'off site' will populate in activity_type. And if not then '95 Modifier' will appear. In addition this form sheet has a field I have checked 'required' yet what is happening is the user is able to enter blanks for activity type. Is there a way within this javascript to then not allow a blank to be entered?
if (getFormElement('activity_type_id').toUpperCase()=='EE641670-8BE3-49FD-8914-030740D9DE72'
&& getFormElement('actual_location').toUpperCase()!='5E74C25C-6363-46BE-B030-16216B364F5A')
{
setFormElement('is_off_site',true);
} else
{
setFormElement('is_off_site',false);
}
{
setFormElement('is_off_site',false);
}
For your requirement custom function might solve your issue. It might cover almost your all primary scenarios. I have tried my best to update an answer with the best possibilities.
Please review it.
function isEmpty(inputValue) {
if(typeof inputValue === 'string' && (inputValue === '0' || inputValue === 'false' || inputValue === '[]' || inputValue === '{}' || inputValue === '')){
return true;
}else if(Array.isArray(inputValue) === true){
return inputValue.length === 0 ? true : false;
}else if(Array.isArray(inputValue) === false && (typeof inputValue === 'object' && inputValue !== null) && typeof inputValue !== 'undefined' && typeof inputValue !== null){
return Object.keys(inputValue).length === 0 ? true : false;
}else if(typeof inputValue === 'undefined'){
return true;
}else if(inputValue === null){
return true;
}else if(typeof inputValue === 'number' && inputValue === 0){
return true;
}else if(inputValue === false){
return true;
}else if(inputValue.length > 0 && inputValue.trim().length === 0){
return true;
}
return false;
}
console.log("isEmpty(' '): ",isEmpty(' '));
console.log("isEmpty(''): ",isEmpty(''));
console.log("isEmpty([]): ",isEmpty([]));
console.log("isEmpty({}): ",isEmpty({}));
console.log("isEmpty(): ",isEmpty());
const nullValue = null;
console.log("isEmpty(null): ",isEmpty(nullValue));
console.log("isEmpty(0): ",isEmpty(0));
console.log("isEmpty(false): ",isEmpty(false));
console.log("isEmpty('0'): ",isEmpty('0'));
console.log("isEmpty('false'): ",isEmpty('false'));
console.log("isEmpty('[]'): ",isEmpty('[]'));
console.log("isEmpty('{}') ",isEmpty('{}'));
console.log("isEmpty(''): ",isEmpty(''));
console.log("isEmpty('0.0'): ",isEmpty(0.0));

Write clever Javascript

this is a very dummy question for all the experts here I suppose.
I have a bunch of if statements (16), and I'm trying to find a way to write 48 lines of code in much less because I'm sure it's possible.
I've read everywhere that long if/else if statements are bad practices.
So how to write this bunch of code the clever way? Thanks
if (!latitude || typeof latitude == 'undefined') {
latitude == 'undefined';
} else if( !longitude || typeof longitude == 'undefined' ) {
longitude == 'undefined';
} else if( !name || typeof name == 'undefined' ) {
name == 'undefined';
} else if( !adresseNum || typeof adresseNum == 'undefined' ) {
adresseNum == 'undefined';
} else if( !adresseVille || typeof adresseVille == 'undefined' ) {
adresseVille == 'undefined';
} else if( !adresseDpt || typeof adresseDpt == 'undefined' ) {
adresseDpt == 'undefined';
} else if( !adresseRg || typeof adresseRg == 'undefined' ) {
adresseRg == 'undefined';
} else if( !adresseFr || typeof adresseFr == 'undefined' ) {
adresseFr == 'undefined';
} else if( !adresseCp || typeof adresseCp == 'undefined' ) {
adresseCp == 'undefined';
} else if( !telephone || typeof telephone == 'undefined' ) {
telephone == 'undefined';
} else if( !horaires || typeof horaires == 'undefined' ) {
horaires == 'undefined';
} else if( !note || typeof note == 'undefined' ) {
note == 'undefined';
} else if( !reviewFinale || typeof reviewFinale == 'undefined' ) {
reviewFinale == 'undefined';
} else if( !website || typeof website == 'undefined' ) {
website == 'undefined';
} else if( !types || typeof types == 'undefined' ) {
types == 'undefined';
} else {
console.log('All fields OK');
}
var isOk = [
latitude,
longtitude,
name,
adresseNum,
adresseVille,
adresseDpt,
adresseRg,
adresseFr,
adresseCp,
telephone,
horaires,
note,
reviewFinale,
website,
types
].every(function (value) {
return !!value;
});
if (isOk) {
console.log('All fields OK');
}
But I think you'd better combine all variables to object or form
you can do a function that checks them all like this
var isDefined = [latitude, longtitude, name, adresseNum, adresseVille, adresseDpt, adresseRg, adresseFr, adresseCp, telephone, horaires, note, reviewFinale, website, types].every(function (value) {return !!value;});
With ES6, you could use an object with all variables as key and value pair, then iterate with Array#every and assign on falsy values undefined and check the result with an if statement.
var data = { latitude, longitude, name, adresseNum, adresseVille, adresseDpt, adresseRg, adresseFr, adresseCp, telephone, horaires, note, reviewFinale, website, types };
if (Object.keys(data).every(k => data[k] || (data[k] = 'undefined', false))) {
console.log('All fields OK');
}
is every variable defined by itself or is it coming from another object or similar to var telephone = obj.telephone?
if that is the case you could do something like this:
var ok = true;
for (var o in obj) {
if (!obj[o]) {
obj[o] == 'undefined';
ok = false;
}
}
if (ok) {
console.log('all fields are ok');
}
An option that might works is using default value in argument destructure. Basically you check for every variable if it's undefined (by the way, what happens if one of those are the value 'false'?).
This is specific for this case though...
function functionWithSomeLogic({
latitude = 'undefined',
longitude = 'undefined',
name = 'undefined',
adresseNum = 'undefined'
// ... and the rest of the variables
}) {
// Do whatever here, all the arguments are initialized or have the string value of 'undefined'
}
by the way, if instead of setting a default value you would like to throw an exception
const throwArg = argName => throw new Error(`Argument missing: ${argName}`);
function functionWithSomeLogic({
latitude = throwArg('latitude'),
longitude = throwArg('longitude'),
name = throwArg('name'),
adresseNum = throwArg('adresseNum')
// ... and the rest of the variables
}) {
// Do whatever here, all the arguments are initialized, if one of them
// had been undefined, an appropriate exception will be thrown before this body
}
A simple es6 function will do the trick. as #Andrey pointed out.
const areDefined = (...args) => args.every(elm => !!elm);
if(areDefined(latitude, longitude, name/*, ...*/)) {
console.log('All fields OK');
}

How to check null and undefined both values for the property?

I have two properties where i need to check null and undefined both for each, how can i use that in if else statements ?
main.js
var validateControlRating = function () {
if ( ($scope.controlProcessRatingDTO.controlPerformanceRatingKey === null ||
$scope.controlProcessRatingDTO.controlPerformanceRatingKey === undefined)
&&
($scope.controlProcessRatingDTO.controlDesignRatingKey === null ||
$scope.controlProcessRatingDTO.controlDesignRatingKey === undefined) ) {
$scope.caculatedRatingDiv = false;
} else {
$http.get('app/control/rest/calculateControlEffectiveness/' + $scope.controlProcessRatingDTO.controlDesignRatingKey + '/' + $scope.controlProcessRatingDTO.controlPerformanceRatingKey).success(function (data) {
$scope.calcaulatedRating = data;
}, function (error) {
$scope.statusClass ='status invalid userErrorInfo';
var errorMessage = error.data.errorMsg;
if (error.data.techErrorMsg) {
errorMessage = error.data.techErrorMsg;
}
$scope.statusInfo = errorMessage;
});
$scope.ratingValidationMsg = '';
$scope.ratingWinValidationClass = 'valid';
$scope.caculatedRatingDiv = true;
$scope.enableRatingSave = false;
}
};
It's a little tedious in javascript, you have to write each condition, and use parentheses etc
if ( ($scope.controlProcessRatingDTO.controlPerformanceRatingKey === null ||
$scope.controlProcessRatingDTO.controlPerformanceRatingKey === undefined)
&&
($scope.controlProcessRatingDTO.controlDesignRatingKey === null ||
$scope.controlProcessRatingDTO.controlDesignRatingKey === undefined) ) {...
or just
if ([null, undefined].indexOf( $scope.controlProcessRatingDTO.controlPerformanceRatingKey ) === -1
&&
[null, undefined].indexOf( $scope.controlProcessRatingDTO.controlDesignRatingKey ) === -1) {...
I think you need to to check this correclty, check for undefined then for null
and use && not || because your code will go to check null value for undefined variable and this surely will throw exception
code:
if( typeof myVar == 'undefined' ? false: myVar )
{ // go here defined and value not null
}
or
code:
if(typeof myVar != 'undefined' && myVar)
{ // go here defined and value not null
}
In your code check will go like
if ((typeof $scope.controlProcessRatingDTO.controlDesignRatingKey !== undefined||
typeof $scope.controlProcessRatingDTO.controlPerformanceRatingKey !== undefined) &&
($scope.controlProcessRatingDTO.controlDesignRatingKey !== null ||
$scope.controlProcessRatingDTO.controlPerformanceRatingKey !== null)) {
// do home work
}else { // do other home work }
You can use negate operator as well, but this would make work for "false" as well:
if (!$scope.controlProcessRatingDTO.controlPerformanceRatingKey && !$scope.controlProcessRatingDTO.controlDesignRatingKey) {
This is a bit shorter but if you want to treat False values separately, then use the Adeneo's answer above.
You could do this:
if ( some_variable == null ){
// some_variable is either null or undefined
}
taken from: How to check for an undefined or null variable in JavaScript?

javascript binary tree, check whether it is a mirror of itself

I learn javascript recently, I don't know why the code I wrote is wrong. Here is the quesion:Given a binary tree, check whether it is a mirror of itself.
var isSymmetric = function(root) {
if(root === null) return true;
function isSymmetric(leftNode, rightNode){
if(leftNode === null && rightNode === null) return true;
if(leftNode === null || rightNode === null) return false;
return (leftNode.val == rightNode.val) && isSymmetric(leftNode.left, rightNode.right) && isSymmetric(leftNode.right, rightNode.left);
}
isSymmetric(root.left, root.right);
};
when the input is 1, the result is "undefined". This algorithm is transformed from my Java code. Please kindly inform me where I get wrong.
var isSymmetric = function(root) {
if (root === null) return true;
function isSymmetric(leftNode, rightNode) {
if (leftNode === null && rightNode === null) return true;
if (leftNode === null || rightNode === null) return false;
return (leftNode.val == rightNode.val) && isSymmetric(leftNode.left, rightNode.right) && isSymmetric(leftNode.right, rightNode.left);
}
return isSymmetric(root.left, root.right);
};
you need to return the result of isSymmetric as shown above
personally, I wouldn't have the outer and inner functions have the same name, it looks confusing to my old eyes :p

testing multiple variables that are object or not

I'm trying to get if both variables are object return true else return false
var sString = "test string";
var oString = new String("test objects");
if( typeof sString == 'object' && typeof oObject == 'object'){
alert('true');
} else {
alert('false');
}
It's alerting fasle. And it's okay.
var sString = new String("some test");
var oString = new String("test objects");
if( typeof sString == 'object' && typeof oObject == 'object'){
alert('true');
} else {
alert('false');
}
It's alerting false. But should return true!
I've tried like this too: typeof sString && oString == 'object' but not working.
I think there's a typo in your code:
if( typeof sString == 'object' && typeof oObject == 'object')
But your variables are called sString and oString. typeof oObject, if oObject is not defined, will return 'undefined', and that's why it alerts 'false'

Categories

Resources