How to use check multiple object properties - javascript

I have an if-statement: if all the properties of an object have values, then the next button will be enabled.
const handleButton = () => {
if(
values.streetAdress !== ""
&& values.postalCode !== ""
&& values.city !== ""
&& values.sex !== ""
&& values.birthName !== ""
&& values.birthPlace !== ""
&& values.birthday !== ""
&& values.country !== ""
&& values.family !== ""
&& values.insuranceID !== ""
){
setDisabeld(false)
}else{
setDisabeld(true)
}
Is there a way to shorten this expression, so all properties will be checked at once?

you can use the Array.prototype.every() method on the values of the object.
const isNotEmpty = Object.values(values).every((v) => v !== '')
if(isNotEmpty) {
setDisabeld(false)
} else{
setDisabeld(true)
}

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

How to exclude specific keys from Array.push()

I'm having trouble excluding items from an Array.push(), I've got something that seems to work, but worry for performance reasons that this may not be the best way to do it:
this.iframe_settings = (localStorage.getItem('iframe_settings') != null) ? JSON.parse(localStorage.getItem('iframe_settings')) : null
var _i = this,
iframeSource = []
const isAffIdSet = (_i.iframe_settings && _i.iframe_settings['cpm_id'] != '' && _i.iframe_settings['cpm_id'] != null) ? true : false
const isSubIdSet = (_i.iframe_settings && _i.iframe_settings['sub_id'] != '' && _i.iframe_settings['sub_id'] != null) ? true : false
Object.keys(this.iframe_settings).forEach(function(key) {
if (key != 'target') {
if (key == 'sub_id') {
if (isAffIdSet && !isSubIdSet) {
_i.iframe_settings['cpm_id'] = _i.iframe_settings['cpm_id']
} else if (isAffIdSet && isSubIdSet) {
_i.iframe_settings['cpm_id'] = `${_i.iframe_settings['cpm_id']}|flex_repay,${_i.iframe_settings['sub_id']}`
} else if (isAffIdSet && !isSubIdSet) {
_i.iframe_settings['cpm_id'] = _i.iframe_settings['cpm_id']
} else {
_i.iframe_settings['cpm_id'] = 'flex_repay'
}
}
iframeSource.push(`&${key}=${_i.iframe_settings[key]}`);
}
});
My code saves an object to iframe_settings, which is null by default. I'd to exclude &target=X from the list of keys retrieved?

Jquery undefined condition is not working

I have set a validation for undefined here below in my javascript code. Even if the value is undefined it is going inside the if condition
if (VSATSaving.PANORAMIC_IMAGES != 'undefined' || VSATSaving.PANORAMIC_IMAGES != "") {
VSATSaving.PANORAMIC_IMAGES = lstPanaromicImages.join();
}
update
Updated code
var PANAROMIC_120 = $(document.getElementById('ImgPanaromic120')).data('imagename');
if (PANAROMIC_120 != "" && PANAROMIC_120 != undefined)
lstPanaromicImages.push(PANAROMIC_120);
var PANAROMIC_150 = $(document.getElementById('ImgPanaromic150')).data('imagename');
if (PANAROMIC_150 != "" && PANAROMIC_150 != undefined)
lstPanaromicImages.push(PANAROMIC_150);
var PANAROMIC_180 = $(document.getElementById('ImgPanaromic180')).data('imagename');
if (PANAROMIC_180 != "" && PANAROMIC_180 != undefined)
lstPanaromicImages.push(PANAROMIC_180);
var PANAROMIC_210 = $(document.getElementById('ImgPanaromic210')).data('imagename');
if (PANAROMIC_210 != "" && PANAROMIC_210 != undefined)
lstPanaromicImages.push(PANAROMIC_210);
var PANAROMIC_240 = $(document.getElementById('ImgPanaromic240')).data('imagename');
if (PANAROMIC_240 != "" && PANAROMIC_240 != undefined)
lstPanaromicImages.push(PANAROMIC_240);
if (VSATSaving.PANORAMIC_IMAGES != undefined || VSATSaving.PANORAMIC_IMAGES != "") {
VSATSaving.PANORAMIC_IMAGES = lstPanaromicImages.join();
}
You used an OR operator. This means that if the VSATSaving.PANORAMIC_IMAGES value is undefined, it is still different from "", that's why the if statement is true.
Just replace the OR operator by an AND:
if (VSATSaving.PANORAMIC_IMAGES !== undefined && VSATSaving.PANORAMIC_IMAGES !== "") {
VSATSaving.PANORAMIC_IMAGES = lstPanaromicImages.join();
}
Note that I removed the single quotes around the undefined keyword.
you can use isNaN function in javascript.
if (!isNaN(VSATSaving.PANORAMIC_IMAGES)) {
VSATSaving.PANORAMIC_IMAGES = lstPanaromicImages.join();
}
if you are using "use strict" in your document then you can use the following way to check:
if (typeof PANAROMIC_120 != "undefined" && PANAROMIC_120 != "")
lstPanaromicImages.push(PANAROMIC_120);
Note that I am using quotes over undefined when I have added typeof
Check undefined condition like as follows
var PANAROMIC_120 = $(document.getElementById('ImgPanaromic120')).data('imagename');
if (PANAROMIC_120 != "" && typeof(PANAROMIC_120) != "undefined")
lstPanaromicImages.push(PANAROMIC_120);
var PANAROMIC_150 = $(document.getElementById('ImgPanaromic150')).data('imagename');
if (PANAROMIC_150 != "" && typeof(PANAROMIC_150) != "undefined")
lstPanaromicImages.push(PANAROMIC_150);
var PANAROMIC_180 = $(document.getElementById('ImgPanaromic180')).data('imagename');
if (PANAROMIC_180 != "" && typeof(PANAROMIC_180) != "undefined")
lstPanaromicImages.push(PANAROMIC_180);
var PANAROMIC_210 = $(document.getElementById('ImgPanaromic210')).data('imagename');
if (PANAROMIC_210 != "" && typeof(PANAROMIC_210) != "undefined")
lstPanaromicImages.push(PANAROMIC_210);
var PANAROMIC_240 = $(document.getElementById('ImgPanaromic240')).data('imagename');
if (PANAROMIC_240 != "" && typeof(PANAROMIC_240) != "undefined")
lstPanaromicImages.push(PANAROMIC_240);
if (typeof(VSATSaving.PANORAMIC_IMAGES) != "undefined" || VSATSaving.PANORAMIC_IMAGES != "") {
VSATSaving.PANORAMIC_IMAGES = lstPanaromicImages.join();
}

How to minimize the if statement in javascript

I have a very long if-conditional statement. How can I minimize it?
Here is my code,
if(this.refs.category.value.trim() != "" &&
this.refs.decisive_min.value.trim() != "" && this.refs.decisive_max.value.trim() != "" &&
this.refs.interactive_min.value.trim() != "" && this.refs.interactive_max.value.trim() != "" &&
this.refs.stabilizing_min.value.trim() != "" && this.refs.stabilizing_max.value.trim() != "" &&
this.refs.cautious_min.value.trim() != "" && this.refs.cautious_max.value.trim() != "" &&
this.refs.aesthetic_min.value.trim() != "" && this.refs.aesthetic_max.value.trim() != "" &&
this.refs.economic_min.value.trim() != "" && this.refs.economic_max.value.trim() != "" &&
this.refs.individualistic_min.value.trim() != "" && this.refs.individualistic_max.value.trim() != "" &&
this.refs.political_min.value.trim() != "" && this.refs.political_max.value.trim() != "" &&
this.refs.altruist_min.value.trim() != "" && this.refs.altruist_max.value.trim() != "" &&
this.refs.regulatory_min.value.trim() != "" && this.refs.regulatory_max.value.trim() != "" &&
this.refs.theoretical_min.value.trim() != "" && this.refs.theoretical_max.value.trim() != ""){
var data = {category:this.refs.category.value.trim()};
data.decisive_min = this.refs.decisive_min.value.trim();
data.decisive_max = this.refs.decisive_max.value.trim();
data.interactive_min = this.refs.interactive_min.value.trim();
data.interactive_max = this.refs.interactive_max.value.trim();
data.stabilizing_min = this.refs.stabilizing_min.value.trim();
data.stabilizing_max = this.refs.stabilizing_max.value.trim();
data.cautious_min = this.refs.cautious_min.value.trim();
data.cautious_max = this.refs.cautious_max.value.trim();
data.aesthetic_min = this.refs.aesthetic_min.value.trim();
data.aesthetic_max = this.refs.aesthetic_max.value.trim();
data.economic_min = this.refs.economic_min.value.trim();
data.economic_max = this.refs.economic_max.value.trim();
data.individualistic_max = this.refs.individualistic_max.value.trim();
data.individualistic_min = this.refs.individualistic_min.value.trim();
data.political_min = this.refs.political_min.value.trim();
data.political_max = this.refs.political_max.value.trim();
data.altruist_min = this.refs.altruist_min.value.trim();
data.altruist_max = this.refs.altruist_max.value.trim();
data.regulatory_min = this.refs.regulatory_min.value.trim();
data.regulatory_max = this.refs.regulatory_max.value.trim();
data.theoretical_min = this.refs.theoretical_min.value.trim();
data.theoretical_max = this.refs.theoretical_max.value.trim();
I just want to check all the values in the form if they are all not empty string.
I used refs by React JS in Meteor.
You could use an array with the wanted keys. Then take only one loop for assigning and checking.
If all values are truthy, data contains the trimmed values, otherwise it is undefined.
var keys = ['category', 'decisive_min', 'decisive_max', 'interactive_min', 'interactive_max', 'stabilizing_min', 'stabilizing_max', 'cautious_min', 'cautious_max', 'aesthetic_min', 'aesthetic_max', 'economic_min', 'economic_max', 'individualistic_min', 'individualistic_max', 'political_min', 'political_max', 'altruist_min', 'altruist_max', 'regulatory_min', 'regulatory_max', 'theoretical_min', 'theoretical_max'],
data = {};
data = keys.every(function (k) {
return data[k] = this.refs[k].value.trim();
}, this) && data || undefined;
Using ES2015, you can do something like that :
Inside your component
const fields = getFields(this.refs);
if (checkFieldsNotEmpty(fields)) {
const data = {category:this.refs.category.value.trim()};
fields.forEach(field => {
data[`${field.name}_min`] = field.valueMin;
data[`${field.name}_max`] = field.valueMax;
});
// ...
}
Outside your component (can be static methods)
const fieldNames = [
'decisive',
'interactive',
'stabilizing',
// ...
];
const getFields = refs => fieldNames.map(name => ({
name,
valueMin: refs[`${fieldName}_min`].value.trim(),
valueMax: refs[`${fieldName}_max`].value.trim()
}));
const checkFieldsNotEmpty = fields => {
for (let field of fields) {
if (field.valueMin === '' || field.valueMax === '') {
return false
}
}
return true;
};
Try using
for (var property in this.refs) {
if (this.refs.hasOwnProperty(property)) {
// perform a null check
if(this.refs[property]){
//perform operaion
data[property] = this.refs[property].trim();
}
}
}

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?

Categories

Resources