Angular 2 ng-class depending on function - javascript

Im trying to change the class of some elements based on an array.
I have declared a function to return a boolean and say if the string(state/class) is contained in the array.
I have call it isState(st: string) {return (this.ArrayWithClasses.indexOf(st) > 0)}
And then I do
[ngClass]="{'class-I-Want-To-Activate': isState('evaluating-this-state') }"
But it is´t working. You see my mistake? A best solution?
Edit: It is working if I use just a boolean to toggle the class. So I consider if function is what is wrong...

You shouldn't check if indexOf() value is > 0, because, if that string is located on the first place in array, you will get 0.
isState(st: string) {
let temp = this.ArrayWithClasses.indexOf(st);
if(temp != -1)
return true;
else
return false;
}
If searched string is not located in the array , you will get -1 value for that.

Use the below
isState(st: string) {
let temp=this.ArrayWithClasses.indexOf(st)
if(temp)
return true;
else
return false;
}

Related

Not able to compare strings in Javascript

I am trying to compare a string with a set of strings stored in an array. Here is the block of code:
then(op => {
if (op[0].probability > FILTER_THRESHOLD) {
if (FILTER_LIST.indexOf(op[0].className) > 1) {
console.log("EUREKA! EUREKA! EUREKA!")
console.log(op[0].className)
return true;
}
}
return false;
})
The second if statement should evaluate to true in some cases but it is not. The return is always false.
op[0].className should be a string and I am also able to get the value from op[0].probability correctly.
What could be the reason?
I have tried debugging and cannot seem to get why the 'if' statement is not being true.
Here is the FILTER_LIST array:
var FILTER_LIST = ["Hello", "Please", "Simple"];
Please advise how I can fix this!
Thank you!
indexOf(...) > 1 asks "did it find a match at the third element or later?" You'll get false if it matched at index 0 or 1. If you want just "it found one anywhere", you want !== -1, >= 0, or to use includes instead of indexOf.
if (FILTER_LIST.indexOf(op[0].className) !== -1) {
// or
if (FILTER_LIST.indexOf(op[0].className) >= 0) {
// or
if (FILTER_LIST.includes(op[0].className)) {

BEGINNER HERE If/else statements with booleans JAVASCRIPT

I am having some trouble with this current lesson on control flow with JavaScript...
The question states:
In this exercise, you will be given a variable, it will be called value.
You will also be given another variable, it will be called greaterThanFive.
Using an 'if statement' check to see if the value is greater than 5. If it is, re-assign the boolean true.
code with stars next to it is the code I was given.
**let greaterThan5 = false;**
if (value > 5 ) {
console.log("That is true");
}
**return greaterThanFive;**
I have tried a number of different ways on how to write the correct code but it obviously is not right.
I tried assigning var value = 10;and then finishing the code as above but it says value has already been assigned. I have tried changing the boolean to let greaterThanFive = true;
The hint only tells me that "should return boolean value equal to 10" and "expected true to be false"
Please help, I have been working on this simple code it may seem for a week and do not want to move on to the next lesson without fully understanding this question.
Thank You!
You have two different variables; greaterThan5 and greaterThanFive.You also have a return statement, which will only work inside of a function.
I believe what you're looking for is something like the following, which passes a value into the function, then checks whether the value is greater than five or not, setting the variable to true inside of the if conditional if it is. The function then returns the greaterThan5 variable's truthiness:
function greater(value) {
let greaterThan5 = false;
if (value > 5) {
greaterThan5 = true;
}
return greaterThan5;
}
console.log(greater(10));
console.log(greater(3));
Which can be further simplified to a simple one-line return statement:
function greater(value) {
return value > 5;
}
console.log(greater(10));
console.log(greater(3));
So, the first clue in the code is the return statement. That means you are likely being asked to write a function that, given some value, checks to see if that value is greater than 5.
Let's define it using your existing code:
function isGreaterThan5(value) {
let greaterThan5 = false;
if (value > 5 ) {
console.log("That is true");
}
return greaterThan5;
}
So right now, we're always going to return false. All you need to do is reassign the value of greaterThanFive if value > 5. So, you can simply do that in your if-statement:
function isGreaterThan5(value) {
let greaterThan5 = false;
if (value > 5 ) {
greaterThan5 = true;
}
return greaterThan5;
}
You can now test your code by calling the function with various values:
isGreaterThan5(1); // returns false
isGreaterThan5(5); // returns false
isGreaterThan5(6); // returns true
And we're done!
I'm wondering if what confused you was the use of let. You might want to read more about var, let, and const.
if (value > 5) {greaterThanFive = true;}

Javascript string index

I am currently working on some javascript on a website that helps companies see how their campaigns are doing on one collective screen. I am using an if statement to help separate some of the information but the when I go to check the code it says
String index out of range -1
Here is the sample code:
var place = {Media Buy Name};
if(place.indexof("Prospecting")){
return "Prospecting";
}
else if(place.indexof("AudienceTargeting")){
return "AudienceTargeting";
}
else if(place.indexof("Retargeting")){
return "Retargeting";
}
else{
return "Other";
}
1) Javascript is case-sensitive. So indexof is not the same as indexOf.
2) Your place variable is an object literal, so it has no methods except Object's ones unless you define a method manually yourself. Another option is making your variable an instance of Array or String which have indexOf method (1, 2).
So you have to either make your place variable an instance of Array/String or define indexOf method manually within place object. Then your code will work.
For if or else if condition indexOf function return int value so you have to compare it with.
If string found then return its index else return -1.
Check the following link:
http://www.w3schools.com/jsref/jsref_indexof.asp
var place = 'Prospecting'; // Can by dynamic
if(place.indexOf('Prospecting') > -1){
return 'Prospecting';
}
else if(place.indexOf('AudienceTargeting') > -1){
return 'AudienceTargeting';
}
else if(place.indexOf('Retargeting') > -1){
return 'Retargeting';
}
else{
return 'Other';
}

How to use IndexOf in JQuery

if($('#this').val().indexOf('4289')){
Do something
else
Do something.
This works only with that 4289,
When I try to add other numbers to be indexed next to it using 'or', it doesn't work. How should I put other number. E.g
IndexOf('4289||78843')
I want this to check this numbers and if the number in the input field is not one of this, to echo error.
Here's more which happens to die when one revisits the field.
$('#Zip').blur(function(){
if (($(this).val().indexOf('0860') > -1)||($(this).val().indexOf('0850') > -1)){
$('#Status_Zip').html("No way.")
$(this).alterClass('*_*', 'Success')
return false;
}else{$('#Status_Code').hide()
$(this).alterClass('*_*', 'Error')
$(this).css('border-color', '#F00').css('background-color', '#FFC').effect("pulsate",{times:4},2)
return true;
}
})
That's because it would be looking for the string '4289||78843', which doesn't exist in the target I'm assuming. Logical operators can't just be tossed in anywhere, only where there are actual values to logically operate on. Something like this:
if(($('#this').val().indexOf('4289') > -1) ||
($('#this').val().indexOf('78843') > -1))
The return value of the indexOf() function is the numeric index of that value in the target value, or -1 if it's not found. So for each value that you're looking for, you'd want to check if it's index is > -1 (which means it's found in the string). Take that whole condition and || it with another condition, and that's a logical operation.
Edit: Regarding your comment, if you want to abstract this into something a little cleaner and more generic you might extract it into its own function which iterates over a collection of strings and returns true if any of them are in the target string. Maybe something like this:
function isAnyValueIn(target, values) {
for (var i = 0; i < values.length; i++) {
if (target.indexOf(values[i]) > -1) {
return true;
}
}
return false;
}
There may even be a more elegant way to do that with .forEach() on the array, but this at least demonstrates the idea. Then elsewhere in the code you'd build the array of values and call the function:
var values = ['4289', '78843'];
var target = $('#this').val();
if (isAnyValueIn(target, values)) {
// At least one value is in the target string
}

finding out if a text input includes a specific text with jquery

what is the best way of finding out if a text input includes a specific text with JQuery?
For example, how can I find out and return a Boolean result if $('#poo').val() includes airport?
EDIT
Here is the solution to my problem thanks to #Niklas;
var IsbtFortxtPropertyHotelNameOn = false;
$('#<%: txtPropertyHotelName.ClientID %>').keyup(function() {
if (/airport/i.test(this.value) && !IsbtFortxtPropertyHotelNameOn) {
$('#<%: txtPropertyHotelName.ClientID %>').btOn();
IsbtFortxtPropertyHotelNameOn = true;
} else if(IsbtFortxtPropertyHotelNameOn && !/airport/i.test(this.value)) {
$('#<%: txtPropertyHotelName.ClientID %>').btOff();
IsbtFortxtPropertyHotelNameOn = false;
}
});
If you want to have control over the case-sensitivity, you could use regex:
if (/airport/i.test(this.value)) alert('true');
It becomes especially useful if you need to check for multiple variables instead of just airport:
if (/(airport|station|docks)/i.test(this.value)) alert('true');
http://jsfiddle.net/niklasvh/tHLdD/
normally you'd do it with either indexOf or split functions, e.g.
$("#textInput").val().split("specifictext").length > 0
there's also Contains Selector:
Description: Select all elements that contain the specified text.
which serves a slightly different purpose but may be of use to you
if($("#elementId").val().indexOf("airport") != -1) {
//Contains "airport"
}
The JavaScript indexOf function returns the index of the first occurence of the specified string. If the string is not found, it returns -1.
Don't really know if it's the best way.. but
function findInpWithTxt(txt) {
var t = null;
$("input[type=text]").each(function() {
if ($(this).val().indexOf(txt) >= 0) {
t = this;
return false;
}
});
return t;
}
this will return the input if found, null if not

Categories