my mind is blank and I can't think of the solution...
I have the following code:
if (onlySelected === true) {
if (r.selected == true) {
result.push(pushValue);
}
}
else {
result.push(pushValue);
}
how can I simplify this code into this:
if (condition) { result.push(pushValue) }
Try this:
if (!onlySelected || r.selected){
result.push(pushValue);
}
or this if you absolutely need the type equality and not just truthiness:
if (onlySelected !== true || r.selected){
result.push(pushValue);
}
if(onlySelected === false || r.selected == true) {
result.push(pushValue);
}
(!onlySelected || r.selected) && result.push(pushValue);
if( (onlySelected === true && r.selected === true) || 1) {
result.push(value)
}
I think this would work:
if(!onlySelected || (onlySelected && r.selected))
result.push(pushValue);
Hm, this is what I made it to.
onlySelected === !0 ? r.selected == 1 && result.push(pushValue) : result.push(pushValue)
Related
I have a simple code with a if statement as follows:
if ((marker.category == str || $("#type").length === 0)
&& (marker.session == session || session.length === 0)) {
marker.setVisible(true);
console.log("session"+session);
} else if (marker.session == session || session.length === 0) {
marker.setVisible(true);
} else {
marker.setVisible(false);
infowindow.close(map, marker1);
}
If I run this code, it always executes the else if condition, but I think the if and else if conditions are different, how to solve this problem? I know the if and else if may have a part of same conditions but with operator && it should be different, right? It has really confused me.
It's quite odd to repeat part of a logical AND in an else if condition. I feel you may be able to understand this better if you refactor the common parts out.
For example
if (marker.session == session || session.length === 0) {
marker.setVisible(true); // same for first two conditionals
if (marker.category == str || $("#type").length === 0) { // &&
console.log("session", session);
}
} else {
marker.setVisible(false);
infowindow.close(map, marker1);
}
If you don't see that console.log(), it clearly means the
marker.category == str || $("#type").length === 0
expression is evaluating as false.
You could even simplify this further by re-using the same boolean values where required. This can eliminate the else blocks which can aid readability. I also think it's odd to conditionally log something so just log it anyway.
let sessionVisible = marker.session == session || session.length === 0
marker.setVisible(sessionVisible)
console.log("session", session);
if (!sessionVisible) {
infowindow.close(map, marker1);
}
if (marker.session == session || session.length == 0) {
marker.setVisible(true);
if (marker.category == str || $("#type").length == 0) {
console.log("session"+session);
} else { }
} else {
marker.setVisible(false);
infowindow.close(map, marker1);
}
this is solved, with this code
if ( (marker.session == session || session.length === 0) && (marker.category == str)){
marker.setVisible(true);
}else if( (marker.session == session || session.length === 0) && (str.length === 0)){
marker.setVisible(true);
}else {
marker.setVisible(false);
infowindow.close(map, marker1);
}
}
that is seem like same condition but different, thanks for you all to help me
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?
Is there a way to simplify this or a more terse form i can use? The logic contained is all correct. It just seems like a lot of returns and else ifs.
mode = (function(mode, current, proposed, origins, destinations) {
if (mode === 'none') {
return 'project';
} else if (proposed.count === 0) {
return 'unseated';
} else if (current.count > proposed.count && proposed.count > 0) {
return 'reducing';
} else if (proposed.count === destinations.count && destinations.count > 1 && current.count === 0) {
return 'newplus';
} else if (proposed.count === destinations.count && current.count === 0) {
return 'new';
} else if (proposed.count > destinations.count) {
return 'increasing';
} else if (proposed.count === destinations.count && destinations.count > origins.count) {
return 'moveplus';
} else {
return 'move';
}
}(moves.register[staff].move, {count: mode.currentDesks}, {count: mode.proposedDesks}, {count: mode.origins}, {count: mode.destinations})));
I previously used a nested ternary which is marginally shorted but i would argue more prone to error and difficult to read (the results are marginally different due to code evolution not errors in replication):
mode =
(moves.register[staff].move === 'none') ? 'project' :
(mode.proposedDesks === 0) ? 'unseated' :
(mode.currentDesks > mode.proposedDesks && mode.proposedDesks > 0) ? 'reducing' :
(mode.proposedDesks === mode.destinations && mode.destinations > 1 && mode.currentDesks === 0) ? 'newplus' :
(mode.proposedDesks === mode.destinations && mode.currentDesks === 0) ? 'new' :
(mode.proposedDesks > mode.destinations) ? 'additional' :
(mode.proposedDesks === mode.destinations && mode.destinations === mode.origins) ? 'move' :
(mode.proposedDesks === mode.destinations && mode.destinations > mode.origins) ? 'moveplus' :
'other';
So while I like the if…then…elseif stack for legibility, it feels like it is more verbose than it could be. I don't think i'm looking for a switch…case version doesn't quite cut it due to the number of comparison variables, and it feels wrong to nest if statements within a switch…case or ternary operators within an if…then…else.
I think instinctively i'd like a form of matrix where the return values are in a grid and somehow a matrix calculation of the the various bitwise conditions returned the correct result. I suspect though that would be a win of compact code over legibility.
Any suggestions?
NB. The variable names including the addition of a count property to each instead of naming the variable as such or not indicating that it is a count are chosen for legibility.
you can use a var to store your choice and return it at the end
mode = (function(mode, current, proposed, origins, destinations) {
var varName='move';
if (mode === 'none') {
varName='project';
} else if (proposed.count === 0) {
varName='unseated';
} else if (current.count > proposed.count && proposed.count > 0) {
varName= 'reducing';
} else if (proposed.count === destinations.count && destinations.count > 1 && current.count === 0) {
varName= 'newplus';
} else if (proposed.count === destinations.count && current.count === 0) {
varName='new';
} else if (proposed.count > destinations.count) {
varName= 'increasing';
} else if (proposed.count === destinations.count && destinations.count > origins.count) {
varName= 'moveplus';
}
}(moves.register[staff].move, {count: mode.currentDesks}, {count: mode.proposedDesks}, {count: mode.origins}, {count: mode.destinations})));
I have this code:
setInterval(function(){
if($("#username_error").val() == "" && $("#password_error").val() == "" && $("#email_error").val() == ""){
$('input[type="submit"]').removeAttr('disabled');
} else {
$('input[type="submit"]').attr('disabled','disabled');
}
}, 10);
I need to disable the submit button if there are no errors for three divs. When I run this code, nothing happens. But if I do an alert() this if statement runs correctly. What am I doing wrong here?
Do it like:
$('input[type="submit"]').attr('disabled','disabled');
$('input[type="text"]').change(function(){
if($("#username_error").val() == "" && $("#password_error").val() == "" && $("#email_error").val() == "") {
$('input[type="submit"]').removeAttr('disabled');
} else {
$('input[type="submit"]').attr('disabled','disabled');
}
});
DEMO
Use jQuery keyup event.
$('input').keyup(function(){
if($("#username_error").val() == "" && $("#password_error").val() == "" && $("#email_error").val() == "") {
$('input[type="submit"]').attr('disabled',true);
} else {
$('input[type="submit"]').attr('disabled', false);
}
});
Another solution...
$(document).ready(function () {
$('button').attr("disabled", true); // starts disabling the button
$('input').on("blur", null, function () {
if ($("#username_error").val() != "" && $("#password_error").val() != "" && $("#email_error").val() != "") {
$("#botao").attr("disabled", false);
} else {
$("#botao").attr("disabled", true);
}
});
});
I have three values:
var tbb = $("#total1 span").text();
var tmb = $("#total2 span").text();
var tab = $("#total3 span").text();
Each of them could be blank.
What is the better way in javascript/jquery check if two of these values is blank?
UPDATE
here is what i mean, my a bit ugly and a "lot of lines" solution
var i = 0;
if (tab != "") {
i++;
}
if (tmb != "") {
i++;
}
if (tbb != "") {
i++;
}
if (i >= 2) {
//do something
}
Any better thoughts?
if(tbb == null || tbb == ''){...}
And the same for the rest.
var twoAreEmpty = $("#total1, #total2, #total3").find("span:empty").length === 2;
var twoblank =
$("#tota11 span, #total2 span, #total3 span")
.filter(function(index){
return !$(this).text().replace(/^\s+|\s+$/g, '');
})
.length === 2;
Also, you probably mean #total1, not #tota11 - just sayin.
if (tab == "") should be enough shouldn't it?
Does .text() ever return blank?
var filtered = [tmb, tbb, tab].filter(function( str ) {
return !str.length;
});
if( filtered.length === 2 ) {
console.log('yay, two empty values: ', filtered);
}
Just try it.
var i = 0;
if(tbb.length == 0 )
{
i++
}
if(tmb.length == 0 )
{
i++
}
if(tab.length == 0 )
{
i++
}
if(i >=2)
{
//perform operation
}
It's been a while, but this is going to be a single-line solution for what you want.
if (((tab == '' ? 1 : 0) + (tmb == '' ? 1 : 0) + (tbb == '' ? 1 : 0)) > 1){
// Do Something
}
All valid answers, but forgetting about undefined :)
if(tbb === '' || tbb === null || tbb === undefined){ // do stuff };
I'd recommend making it a function which could return true/false :)