logic in if/else method in javascript - javascript

i just want to implement if else method in my apps
the problem is when in choose the first if it working, but if i choose second if its not working, this is my code
//filter in session
filterMarkersx = function (session) {
var table = $('#edcTable').DataTable().column(1).column(2);
var str;
$("select#type option:selected" ).each(function() {
str = $(this).val();
});
for (i = 0; i < gmarkers1.length; i++) {
marker = gmarkers1[i];
if(marker.session == session || session.length === 0) {
marker.setVisible(true);
} else if(marker.session == session || session.length === 0) {
if (marker.category == str || $("#type").length === 0){
marker.setVisible(true);
}
}else{
marker.setVisible(false);
infowindow.close(map, marker1);
}
}
table.search(str).draw();
}
anyone can help me what must i do, thanks in advance.
-kraken.

Your if and else if conditionals are exactly the same. The else if block can never execute, since if its conditional is true, then the first if is true, so its else isn't even looked at.

Related

if statement executes code under wrong condition

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

Skip Iteration Google Apps Script

I have a very simple For Loop in Google Apps Script to check some conditions in a Google Sheet. What I want is to add another condition, if it is met, then I want to skip current iteration and move on to next. This is pretty easy in VBA, but I am not sure how to do it on JavaScript.
Current code:
for (var i=1 ; i<=LR ; i++)
{
if (Val4 == "Yes")
{
// Skip current iteration... <-- This is the bit I am not sure how to do
}
elseif (Val1 == "Accepted" && !(Val2 == "") && !(Val3 == ""))
{
// Do something..
}
else
{
// Do something else...
}
}
continue statement can be used to continue to next itteration :
for (var i=1 ; i<=LR ; i++)
{
if (Val4 == "Yes")
{
continue; // Skip current iteration...
}
// Do something else...
}
In your sample case, leaving the if block empty will achieve the same result:
for (var i=1; i <= LR; i++)
{
if (Val4 == "Yes")
{
}
elseif (Val1 == "Accepted" && !(Val2 == "") && !(Val3 == ""))
{
// Do something..
}
else
{
// Do something else...
}
}

Cookie seems not to work

Since i needed to have some variables of my programs available in all the pages, i decided to use cookies (js-cookie).
if ((Cookies.get('j') == null) || (Cookies.get('j') == 0)) {
Cookies.set('j', 0);
var j = parseInt(Cookies.get('j'));
}
Cookies.set('imuno');
var imuno = Cookies.get('imuno');
Cookies.set('imdue');
var imdue = Cookies.get('imdue');
Then i wrote two functions:
function check1(){
if ((src1 == "") || (src1 == "undefined")) {
alert("Selezionare un'immagine.");
}
else {
controllo();
}
}
and
function check2(){
if ((src2 == "") || (src2 == "undefined")) {
alert("Selezionare un'immagine.");
}
else {
controllo();
}
}
As you can see, they're two check functions that retrieve another function (controllo()) which works like that:
function controllo() {
if (j == 0) {
alert(j);
imuno = src1;
Cookies.set('imuno', src1);
alert(imuno);
location.href = "schienale.html";
j++;
Cookies.set('j', 1);
}
else if (j == 1){
alert(j);
imdue = src2;
Cookies.set('imdue', src2);
alert(imuno,imdue);
location.href = "riep.html";
j++;
Cookies.set('j', 2);
}}
All this code is written in my external .JS file. Now the funcion check1() works perfectly, but when the check2() start running the program doesn't work anymore, as if the cookie j doesn't mantain its value. How can i solve? Thanks all!

Uncaught TypeError: Cannot read property 'indexOf' of undefined in angularjs

I am very new to the world of coding, and need some help from experts. Below is the angularJs error I have noticed in the file:
The error is being pointed to this:
if( searchItemsSmallLetters.indexOf(searchTextSmallLetters) !== -1){
Your assistance will be much appreciated.
I am trying to give user suggestion based on the key which user enters.
var app = angular.module('app',[]);
app.controller('autoCompleteCTRL', function($scope, $rootScope,$http){
$rootScope.searchItems = [];
var arr= getCountries(); // Load all countries with capitals
function getCountries(){
$http.get("ajax/getCountries.php").success(function(data){
for(var i=0;i<data.length;i++)
{
$rootScope.searchItems.push(data[i].bvl_area);
}
return $rootScope.searchItems;
});
};
//Sort Array
$rootScope.searchItems.sort();
//Define Suggestions List
$rootScope.suggestions = [];
//Define Selected Suggestion Item
$rootScope.selectedIndex = -1;
//Function To Call On ng-change
$rootScope.search = function(){
$rootScope.suggestions = [];
var myMaxSuggestionListLength = 0;
for(var i=0; i<$rootScope.searchItems.length; i++){
var searchItemsSmallLetters = angular.lowercase($rootScope.searchItems[i]);
var searchTextSmallLetters = angular.lowercase($scope.searchText);
if( searchItemsSmallLetters.indexOf(searchTextSmallLetters) !== -1){
$rootScope.suggestions.push(searchItemsSmallLetters);
myMaxSuggestionListLength += 1;
if(myMaxSuggestionListLength == 5){
break;
}
}
}
}
//Keep Track Of Search Text Value During The Selection From The Suggestions List
$rootScope.$watch('selectedIndex',function(val){
if(val !== -1) {
$scope.searchText = $rootScope.suggestions[$rootScope.selectedIndex];
}
});
//Text Field Events
//Function To Call on ng-keydown
$rootScope.checkKeyDown = function(event){
if(event.keyCode === 40){//down key, increment selectedIndex
event.preventDefault();
if($rootScope.selectedIndex+1 !== $rootScope.suggestions.length){
$rootScope.selectedIndex++;
}
}else if(event.keyCode === 38){ //up key, decrement selectedIndex
event.preventDefault();
if($rootScope.selectedIndex-1 !== -1){
$rootScope.selectedIndex--;
}
}else if(event.keyCode === 13){ //enter key, empty suggestions array
event.preventDefault();
$rootScope.suggestions = [];
}
}
//Function To Call on ng-keyup
$rootScope.checkKeyUp = function(event){
if(event.keyCode !== 8 || event.keyCode !== 46){//delete or backspace
if($scope.searchText == ""){
$rootScope.suggestions = [];
}
}
}
//======================================
//List Item Events
//Function To Call on ng-click
$rootScope.AssignValueAndHide = function(index){
$scope.searchText = $rootScope.suggestions[index];
$rootScope.suggestions=[];
}
//======================================
});
The value of searchTextSmallLetters variable has become undefined. First you check whether it can be undefined. If so change the line to
if(searchItemsSmallLetters && searchItemsSmallLetters.indexOf(searchTextSmallLetters) !== -1){
or else check the service on "ajax/getCountries.php" is working and return the expected output. Since you using a get request you can use browser to do that (%domain%/ajax/getCountries.php eg:-localhost:8080/ajax/getCountries.php)
Important: Always it is good to do validations. So it is good to change the line to
if(searchItemsSmallLetters && searchItemsSmallLetters.indexOf(searchTextSmallLetters) !== -1){
Change the below line for proper handling
if( searchItemsSmallLetters.indexOf(searchTextSmallLetters) !== -1){
To
if(searchItemsSmallLetters && searchItemsSmallLetters.indexOf(searchTextSmallLetters) !== -1){
When "searchItemsSmallLetters" is undefined, then your condition will throw such error.

JS Basics: How to use if/else inside a function and set to variable

I'm a JavaScript total beginner and I've gotten stuck on something that seems like it should work while trying to set a variable with a an if/else condition inside and anonymous function. Here is my code:
function changeValue(){
var newValue = (function(){
var getRadioValue = $( "input:radio[name=Radio1]:checked" ).val();
if (getRadioValue === 5){
var final = 8;
}
else if (getRadioValue === 4){
var final = 5;
}
else if (getRadioValue === 3){
var final = 3;
}
else if (getRadioValue === 2){
var final = 1;
}
else if (getRadioValue === 1){
var final = -1;
}
else
{
var final = 0;
}
return final;
})();
alert(newValue);
}
Right now, the alert is showing 0 because none of the "ifs" are returning true, but if I set the getRadioValue variable hard coded like:
var getRadioValue = 5;
then the if/else conditional works and the alert message shows 8. That makes it seem like the .val() method isn't working. However, if I simply set the alert to:
alert(getRadioValue);
The alert message does in fact display the correctly selected radio value from the radio button set on my page. So I know that is working... Now I can't figure out where I'm going wrong. It seems like since the radio value is getting assigned to getRadioValue correctly, and the conditional is working, the whole thing should work. I'm sure it's such a basic problem, but after much research I still can't seem to get it. Any help is greatly appreciated!
.val() is returning a string but you are testing for number if (getRadioValue === 5){.
You might want to do getRadioValue = parseInt(getRadioValue) first.
Demo:
getRadioValue = parseInt("5")
var final = 0; // use var once, its cleaner ;)
if (getRadioValue === 5) {
final = 8;
} else if (getRadioValue === 4) {
final = 5;
} else if (getRadioValue === 3) {
final = 3;
} else if (getRadioValue === 2) {
final = 1;
} else if (getRadioValue === 1) {
final = -1;
}
alert(final);
Thanks to CodeiSir! That was the issue. Here is my final working code for others who might run into a similar problem:
function changeValue(){
var newValue = (function(){
var getRadioValue = $( "input:radio[name=CalcItem1]:checked" ).val();
var RadioValue = parseInt(getRadioValue);
if (RadioValue === 5){
var final = 8;
}
else if (RadioValue === 4){
var final = 5;
}
else if (RadioValue === 3){
var final = 3;
}
else if (RadioValue === 2){
var final = 1;
}
else if (RadioValue === 1){
var final = -1;
}
else
{
var final = 0;
}
return final;
})();
alert(newValue);
}

Categories

Resources