my If Else condition not working properly in React.js - reactjs

I am saving a record on button click but it always throwing an error.
I am including an if else condition. I have surpassed all the conditions but still my code is going to the if condition but It should not go to if condition.
code is -
my this.state.question.options value is -
[
{
id:3250,
label:'good answer',
assert:1
position:1
},
{
id:3249,
label:'bad answer',
assert:0
position:2
}
]
and I am checking if else condition as -
if (this.state.question.options.filter(o => o.assert === true).length <= 0) {
hasError = true
errorKey = 'add-question-modal-missing-assert-options'
}
else {
alert("test");
}
my code should goto else part and print test as alert but it is going to if part and showing error. Why ?
I wanna show else part i.e test as alert

You are using the strict comparison operator (===) while comparing 2 different values. In your example, 1 is being parsed as an integer, while true is being parsed as a boolean. A strict comparison operator is used to check 2 values on equal values AND equal types.
To fix the error in your code, use a loose comparison (==) or convert the integer to a boolean by using !!1

if (this.state.question.options.filter((el) => {return !!el.assert}).length <= 0) {
hasError = true
errorKey = 'add-question-modal-missing-assert-options'
}
else {
alert("test");
}

In JavaScript, 1 is not strictly equal to true. However, it is a good practice to use the strict equality operator ===.
You should compare o.assert with the real possible value o.assert === 1.
In terms of readability I would also consider comparing the length to 1 instead of 0:
this.state.question.options.filter(option => option.assert === 1).length < 1

this.state.question.options value is -
[
{
id:3250,
label:'good answer',
assert:1,
position:1
},
{
id:3249,
label:'bad answer',
assert:0,
position:2
}
]
and then
if (this.state.question.options.filter(o => o.assert == true)).length <= 0) {
hasError = true
errorKey = 'add-question-modal-missing-assert-options'
} else {
alert("test");
}
replace === strict type with ==

Do u want this kind of code
if (this.state.question.options.length <= 0) {
assert = true;
hasError = true;
errorKey = 'add-question-modal-missing-assert-options'
}
else {
alert("test");
}

Related

single requirement in parsley error message %s1

Hi I have a custom validator with 2 requirements(arguments/paramaters) in parsley.js
For the error message I only want to display one of the requirements but I cannot work out how
messages: {en: 'You must choose at least one language with %s'},
I thought %s1 or %s0 might work but they don't
%s results in this message:
You must choose at least one language as [native,enrolment_form_new_instruction_languages_proficiency]
but I just want
You must choose at least one language as native
here is my full validator in case that helps you answer:
Parsley.addValidator('oneChildEquals', {
requirementType: ['string', 'string'],
validateString: function(_value, requirement, requirement2, instance) {
var $inputs = $(instance.element).find("select.language-proficiency");
var valid = false;
$inputs.each(function(i){
if($(this).val() == requirement){
valid = true; // one input has the target value (requirement2)
return false; //break out of the loop
}
});
// no input has the target value (requirement2)
return valid;
},
messages: {en: 'You must choose at least one language with %s'},
});
I have written a solution, probably could be improved, but I don't even know if I need this now. Anyway in case anyone else does, you can just add this code:
if(typeof(string) === 'string' && typeof(parameters) === 'string' && parameters.match(/^\[.*\]$/) && string.match(/\%s\d/)){
//parameters are an array of values and string is trying to access them individually with %s1 to get first etc
var paramsArray = parameters.slice(1, parameters.length-1).split(',');
var interpolations = string.match(/\%s\d/g);
for(var j = 0; j < interpolations.length ; j++){
var interpolation = interpolations[j];
var number = parseInt(interpolation.replace("%s", ''));
if(isNaN(number)){
string = string.split(interpolation).join(interpolation + '[not a valid interpolation]');
}else {
var val = paramsArray[number-1];
if(typeof(val) === 'undefined'){
val = interpolation + '[not a valid interpolation]';
}
string = string.split(interpolation).join(val);
}
}
return string
}
after this code in the source
formatMessage: function formatMessage(string, parameters) {
if ('object' === _typeof(parameters)) {
for (var i in parameters) {
string = this.formatMessage(string, parameters[i]);
}
return string;
}
and before
return 'string' === typeof string ? string.replace(/%s/i, parameters) : '';
Then it supports things like
Parsley.addValidator('testParsley', {
requirementType: ['string','string'],
validateString: function(_value, requirement, requirement2) {
return (_value === requirement || _value === requirement2);
},
messages: {en: 'test parsley this field must equal %s1 or %s2'}
});

using lodash _find to return true or false

I'm trying to use lodash function to find if it satisfies the if statement. When the code has run the code which 'return false', it stills continue execute the _find function and did not return the result (boolean value) in the scope.onToggle.
$scope.onToggle = function(disposition) {
if (requiredFieldsEntered()===false){
// if return value from the function is false, alert user
}
}
function requiredFieldsEntered(){
var res = _.find($rootScope.CustomFields,
function(field){
if(field.enabled && field.required){
if(field.table_name === 'session'){
if(!$scope.session.external_id){
console.log(field.column_name);
return false;
}
else if (field.table_name === "session_extension"){
if(!$scope.session.extension|| ($scope.session.extension && !$scope.session.extension[field.column_name])){
console.log(field.column_name);
return false;
}
}
}
}});
if (res) return false;
else return true;
}
First let's stop and consider what _.find actually does. It loops over an array and returns the first element of the array that matches the condition.
_.find([1, 2, 3, 4], function(num) { return num % 2 === 0 });
// returns 2
In the case of your _.find function, then, you'll either get back one of the fields from $rootScope.CustomFields or undefined if none of the fields returns a truthy value from function(field)….
Here is where you have your problem. The anonymous function function(field)… only ever returns false. You need to return true if you find an error, or else return false otherwise.
Since your requiredFieldsEntered() function is ultimately trying to return either true or false, you can decide which of those to return based on whether or not your _.find function returns some object or undefined.
Something like this:
$scope.onToggle = function(disposition) {
if (requiredFieldsEntered()===false){
// if return value from the function is false, alert user
}
}
function requiredFieldsEntered(){
const fieldWithErrors = _.find($rootScope.CustomFields,
function(field){
let result = true;
if(field.enabled && field.required){
if(field.table_name === 'session'){
if(!$scope.session.external_id){
console.log(field.column_name);
result = false;
} else if (field.table_name === "session_extension"){
if(!$scope.session.extension|| ($scope.session.extension && !$scope.session.extension[field.column_name])){
console.log(field.column_name);
result = false;
}
}
}
}
return result;
});
if (fieldWithErrors) {
return false;
}
return true;
}
Quick note that a shorter but somewhat less-readable version at the end may replace this bit:
…
if (fieldWithErrors) {
return false;
}
return true;
}
With:
…
return !!!fieldWithErrors;
The first two exclamation points would be typecasting the result of your find function to either true if it comes up with something or false if it returns undefined, and then the third exclamation point would invert that boolean to match your current scheme of returning false if there are errors.
(Or you could change your function name to errorsArePresent and return true – !!fieldWithErrors).

typescript filter array on 2 parameters

In order to filter an array on possibly 2 parameters I have written the following code:
filterStudies(searchString?: string) {
if (searchString && !this.selectedModalityType) {
this.studies = this.fullStudyList.filter(function (study) {
return (study.Code.toUpperCase().includes(searchString.toUpperCase())) ||
(study.Description.toUpperCase().includes(searchString.toUpperCase()));
})
} else if (!searchString && this.selectedModalityType) {
console.log(this.selectedModalityType)
this.studies = this.fullStudyList.filter(function (study) {
return (study.ModalityType.Code.toUpperCase() === this.selectedModalityType.toUpperCase())
})
} else if (searchString && this.selectedModalityType) {
this.studies = this.fullStudyList.filter(function (study) {
return (study.Code.toUpperCase().includes(searchString.toUpperCase())) ||
(study.Description.toUpperCase().includes(searchString.toUpperCase())) &&
(study.ModalityType.Code.toUpperCase() === this.selectedModalityType.toUpperCase())
})
}
}
filterStudies(searchString?: string) is called when typing in a textbox that.
The other way of filtering could be by selecting a value from a dropdown box. Achieved by this code:
handleSelection(value:any){
this.selectedModalityType = value;
console.log(value)
this.filterStudies()
}
All works fine until this code is hit:
this.studies = this.fullStudyList.filter(function (study) {
return (study.ModalityType.Code.toUpperCase() === this.selectedModalityType.toUpperCase())
})
Error message : ERROR TypeError: Cannot read property 'selectedModalityType' of undefined, I see it is actually logged in the line before.
What am I missing??
Thanks,
In your funtcion, this is not the same this as the line before.
This will work:
let self = this;
this.studies = this.fullStudyList.filter(function (study) {
return (study.ModalityType.Code.toUpperCase() === self.selectedModalityType.toUpperCase())
})
You can read this to learn more: https://github.com/Microsoft/TypeScript/wiki/%27this%27-in-TypeScript
The this keyword in JavaScript (and thus TypeScript) behaves differently than it does in many other languages. This can be very surprising, especially for users of other languages that have certain intuitions about how this should work.
(...)
Typical symptoms of a lost this context include:
A class field (this.foo) is undefined when some other value was expected

AngularJS - What is the best way to detect undefined null or empty value at the same time?

Sometimes I need to check a value for three conditions at the same time, null, undefined or "". Due that I haven´t found any method to do this, I coded my own and it works.
$scope.isNullOrEmptyOrUndefined = function (value) {
if (value === "" || value === null || typeof value === "undefined") {
return true;
}
}
Just wanted to know if there is a better way to accomplish the same thing.
Thanks so much in advance,
Guillermo
How about this? Since you seem to be returning true in those null/undefined cases:
$scope.isNullOrEmptyOrUndefined = function (value) {
return !value;
}
http://jsfiddle.net/1feLd9yn/3/
Note that an empty array and empty object will also return false as they are truthy values. If you want the true/false return to be flip-flopped, then omit the ! before value.
Update
As mentioned in the comments it's better to use return !value.
$scope.isValid = function(value) {
return !value
}
Old and incomplete Answer
A proper way is simply to use angular.isDefined()
**AngularJS - What is the best way to detect undefined null or empty value at the same time?**
You can define a function or you can use inline command.
$scope.isNullOrUndefined = function(value){
return (!value) && (value === null)
}
or
var temp = null;
(temp) ? 'I am not null' : 'yes I am null or undefined';
"yes I am null or undefined"
var temp = undefined
(temp) ? 'I am not null' : 'yes I am null or undefined';
"yes I am null or undefined"
temp = '123123Rec'
(temp) ? 'I am not null' : 'yes I am null or undefined';
"I am not null"
I tried the below code, it's working perfect in my angular js application.
function isValid(value) {
return typeof value !== 'undefined';
};

Extjs checkbox setValue based on 1 and 0

I have a checkbox on my form panel,
And I'm on the process where I need to edit a data based on id in MySQL database where there is a option for checkbox 1=checked 0=not checked,
how do I get the value of, for example, the field of checkbox and put it on a conditional clause and set the value checked to checkbox if it is 1 and not checked if it returns 0?...
Need to set to the checkbox config
inputValue: '1',
uncheckedValue: '0'
You can check the documentation at http://docs.sencha.com/extjs/4.2.2/#!/api/Ext.form.field.Checkbox-cfg-uncheckedValue
All checks do not consider the event check if the value is a string. I created a fix. Add before Ext.onReady
Ext.override
(
Ext.form.Checkbox,
{
setValue:function(v){
var checked = this.checked, inputVal = this.inputValue;
if(v === false)
{
this.checked = false;
}
else
{
this.checked = (v === true || v === 'true' || v == '1' || (v instanceof String) || (inputVal ? v == inputVal : String(v).toLowerCase() == 'on'));
}
if(this.rendered)
{
this.el.dom.checked = this.checked;
this.el.dom.defaultChecked = this.checked;
}
if(checked != this.checked)
{
this.fireEvent('check', this, this.checked);
if(this.handler)
{
this.handler.call(this.scope || this, this, this.checked);
}
}
return this;
}
}
);
{
xtype:'checkbox',
fieldLabel:'Caption',
labelSeparator:':',
boxLabel:'LabelText',
name:'status',
inputValue:'0'
}
inputValue must be a String '0'.
this issue has been resolved,
by using 1 checkbox per field, there is no problem at all!....
the checkbox will get checked when the fieldname assigned to it returns a value of 1,
that's it!,
....

Resources