Append class with if statement - javascript

I just created a variable for a specific site of mine but I want to append a class entitled "partner-text" if I'm actually on that site. If I'm on a different site then don't append it. How can I do that?
use(function() {
var inPartnerPath = currentPage.getPath().indexOf("partners_Skate_Daily");
// to check if the site is under partners_Skate_Daily folder if yes then it should return true
var isPartner = (inPartnerPath != -1) ? 'true' : 'false';
return {
isPartner: isPartner
};
});

'true' and 'false' are strings. You want to use the boolean values true/false.
You don't even need the ?: here, != already returns you a boolean.
var isPartner = inPartnerPath != -1;

Related

ng-show based on dynamic conditions from database

We are working on some dynamic form where user can create questions in the admin panel and put conditions to show them based on other questions values.
ng-show="((UserCode==10003 && Name=='Ankur') ||(StateId=='NY'))"
this works fine show/hide question based on other questions value, But the conditions are dynamic and created runtime based on the users selected values in database.. how can we add ng-show conditions dynamic ?
I tried this
$scope.Condition = "((UserCode==10003 && Name=='Ankur') ||(StateId=='NY'))";
and ng-show="{{Condition}}" but this didn't worked.
UserId, Name & StateId are other questions on the page.
Please let me know if i missed some info.
thanks
Try with method:
ng-show="condition()"
$scope.condition = function() {
/* You calculate your condition here */
var condition = ... ;
return condition;
}
You know this is a string and not a condition that will return true or false.. ?
$scope.Condition = "((UserCode==10003 && Name=='Ankur') ||(StateId=='NY'))";
This should be correct
$scope.Condition = (UserCode==10003 && Name=='Ankur') ||(StateId=='NY');
$scope.Condition = "((UserCode==10003 && Name=='Ankur') ||(StateId=='NY'))";
this will never work because it is not a function or condition that returns a true or false,
try with thist
$scope.condition = function(_usercode, _name, _state_id){
return (UserCode == _usercode && Name == _name) || (StateId == _state_id);
}
and in html ng-show="condition(10003,'Ankur','NY')"

Is it correct to execute a function inside IF else statement?

The isCheck() function returns false if not radio buttons have been checked.
if (isCheck() === false) {
i = 0;
return i;
}
yes it works. alternatively you could use ternary operator
using that syntax:
test ? expression1 : expression2
for example :
//init var i with some value
var i = 1;
function isCheck(){ return false;}
i = isCheck() === false ? 0 : i;
return i;
or simple:
//before you should initialize i
return !isCheck() ? 0 : i ;
There is no wrong in executing a function inside if conditional statement.
For such case you can use ternary operator
var i=-1; // Note var key word & initialized with some value
isCheck() === false ? (i=0):(i=someOtherVal)
I don't see why not, some will say its not conventional but it should work just fine!
Yes it is correct
You dont need to create a variable only to receive a bool and later do a validation you can do directly.

logic error in javascript code

I am trying to write some logic that will check for the existence of a specific record in two tables.
If the row exists in either table, I want to return TRUE.
For table A, when the record is added to the table, the id field looks like "123".
For table B, the same record would have the id of "a123". However, the value i have to search for the record is "row_123".
This is what my code looks like right now :
var checkForDuplicates = function(row_id) {
return !!($('#existing_members').find('#' + row_id.replace('row_','')).length || $('#selected_users').find('#' + row_id.replace('row_','a').length) );
};
I want the function to return true if the record exists in either table.
However, this statement returns true in cases when it should be false.
What I've tried so Far
I've been playing around in the console to make sure that my logic is correct:
!!(1 || 0) //returns true
!!(0 || 0) //returns false
!!(0 || 1) //returns true
I'm also currently reviewing the replace statements to make sure the find() is being supplied the right strings.
But a second pair of eyes to confirm that my logic is correct would be appreciated.
Thanks
EDIT 1
The solution, using Max's suggestion would be:
var checkForDuplicates = function(row_id) {
var parts = row_id.split('_');
var tableB = '#a'+ parts[1];
var tableA = '#' + parts[1];
return !!($('#existing_members').find(tableA).length || $('#selected_users').find(tableB).length);
}
However, as Ankit points out, I just had a typo in my original code. So this would be my final answer / solution:
var checkForDuplicates(row_id) {
return !!( $('#existing_members').find('#' + row_id.replace('row_', '')).length || $('#selected_users').find('#' + row_id.replace('row_','a')).length);
}
Your code has a typo at the end of return statement
...'a').length)); //it returns object which always evaluates to true
it should be
...'a')).length);
DEMO
var checkforduplicates = function(row_id){
//row_id looks like "row_123"
return !!($('#tableA').find('#' + row_id.replace('row_','')).length || $('#tableB').find('#' + row_id.replace('row_','a')).length );
}
alert(checkforduplicates("row_123"));
<table id=tableA><tr><td id="123">123 ID</td></tr></table>
<table id=tableA><tr><td id="a13">a13 ID</td></tr></table>
Corrected few issues to make the code more efficient:
var checkforduplicates = function(row_id) {
var id = row_id.split('_')[1]; // [ 'row', '123']
return $('#'+id).length || $('#a'+id).length;
}
No need for !! as operator || produces boolean result (true or
false)
Used $('#'+id) as more efficient jQuery selector
Removed unnecessary find(..) call
Eliminated unnecessary parenthesis (which had an issue)
I want the function to return true if the record exists in either table.
var checkForDuplicates = function(row_id) {
row_id = row_id.substring(4); // 'row_123' -> '123'
var table_A_row_id = row_id;
var table_A_row_exists = $('#tableA').find('#' + table_A_row_id).length > 0;
var table_B_row_id = 'a' + row_id;
var table_B_row_exists = $('#tableB').find('#' + table_B_row_id).length > 0;
return table_A_row_exists || table_B_row_exists;
};
of course it is returning the opposite of the things you want, cause you are using !!.
! is used to negotiate the return value of the specific function/variable e.g.:
if(!var_x == false)
this example only works if var_x is true.
So please be aware to avoid !! ;)
Please use a single ! instead!

Javascript comparing boolean value to True

I am trying to compare a database (SQL) value (which is being returned correctly) to the boolean value 'true'. If the database bit value is = true then I want a div element to become visible, else stay hidden.
<script language="javascript">
window.onload= function show_CTL() {
if(<%=_CurrentUser.IsCTL%> == true){
document.getElementById('CTL').style.visibility = "visible";
} else{
document.getElementById('CTL').style.visibility = "hidden";
}
}
</script>
However I am getting the error, Javascript: 'True' is undefined.
I have tried many combinations of <%=_CurrentUser.IsCTL%> == 'true' or "true" or true or "True" or 'true' and even the === ... but all give me the same error message.
Any insights on how to resolve this issue will be greatly appreciated.
I have such comparisons successfully before with integer values such as:-
window.onload= function show() {
if(<%=_CurrentUser.RoleKey%> == 1 || <%=_CurrentUser.RoleKey%> == 2)
document.getElementById('enr').style.visibility = "visible";
else
document.getElementById('enr').style.visibility = "hidden";
}
Do this:
if("<%=_CurrentUser.IsCTL%>" === "True")
<%=_CurrentUser.IsCTL%> is returning True. So wrap it with string and compare them instead. Notice the '===' instead of '=='.
In
if(<%=_CurrentUser.IsCTL%> == true)
I think <%=_CurrentUser.IsCTL%> is getting evaluated to True before the code is seen by the browser.
The browser will see this as
if(True == true)
True does not make a lot of sense to the browser, thats why the error. For this true to be treated as a boolean, try one of this:
if(new Boolean('<%=_CurrentUser.IsCTL%>') == true)
or
if(new Boolean('<%=_CurrentUser.IsCTL%>'))
This has gotten me before as well. ASP.NET will return True for a boolean which is true. You have to make it a string and then compare it to the string version == "True" in order to get a proper conditional statement.
Conversely, you could also just make a variable in javascript
var True = true;
You need to convert your native boolean value to the string "true" before output. So, assuming ASP.NET MVC, I believe it looks like:
<%=_CurrentUser.IsCTL ? "true" : "false"%>

Greasemonkey testing if array element exists

I'm writing a script that adds labels to things on a page using an element from an array based on part of the link... so my array looks like this:
var componentList[9] = "Sunnyseed"
var componentList[10] = "Echoberry"
var componentList[11] = "Riverstone"
var componentList[13] = "Auraglass"
var componentList[14] = "Skypollen"
You'll notice there is no '12'... I want the label to be 'Unknown' when the array item doesn't exist. Now, I can't exactly test my solution since I can't cause the target page to throw me a 12... so I was hoping somebody would tell me whether this will do what I want or not...
var component = ""
if(typeof componentList[critterIDval] == 'undefined'){
component="Unknown"
}
else{
component=componentList[critterIDval]
}
This is obviously not the full script, but it should be the important stuff... I just want to know if that will make it say 'Unknown' when the critterIDval is 12 - since it could take years to come across the situation for testing.
You're pretty much there. You're using a single-equals sign in your comparison, so that will mess it up, and I'm not sure you can create a JS array like that, but aside from that, you're good.
Here is the test I ran for it:
var componentList = [];
componentList[9] = "Sunnyseed";
componentList[10] = "Echoberry";
componentList[11] = "Riverstone";
componentList[13] = "Auraglass";
componentList[14] = "Skypollen";
for (var critterIDval = 9; critterIDval < 15; critterIDval++) {
if (typeof componentList[critterIDval] == 'undefined') { // double equals here
component = "Unknown";
} else {
component = componentList[critterIDval];
}
console.log(component);
}
It looks fine.
Though if you are sure that the value will never be an empty string(like componentList[14] = '';) then you can try
var component = componentList[critterIDval] || 'Unknown'
I want the label to be 'Unknown' when the array item doesn't exist.
The typeof operator does not tell you if a property exists or not as it returns undefined when the property doesn't exist but also when it does exist and has been assigned a the value undefined or simply created but hasn't been assigned a value.
There are two primary ways to test for the existence of a property: the in operator, which also looks on the [[Prototype]] chain and the hasOwnProperty method of all Objects. So
if (componentList.hasOwnProperty(critterIDval)) {
component = "Unknown"
} else {
component = componentList[critterIDval]
}
which you could also write as:
component = componentList.hasOwnProperty(critterIDval)? componentList[critterIDval] : 'unknown';
PS. there are other methods, such as looking at Object.keys(componentList) and componentList.propertyIsEnumerable(critterIDval), but the above are the most common.
Edit
If your requirement is not just to test for property existence but to also test for a "truthy" value, then:
if (componentList[critterIDval])
may be sufficient and will return false where the value is '' (empty string), 0, false, NaN, undefined or null.
Maybe just testing for a non–empty string or number will do:
if (/.+/.test(componentList[critterIDval]))
but that returns true for NaN, null and so on. So you need to specify what you are actually testing for, otherwise you may get undesired results for some values.

Categories

Resources