ng click if true, resolves to true when false - javascript

I have a ng-click event on an <i> tag that looks like this:
ng-click="parent.Status != 'Open' || (item.Status='Retrospect')"
So if parent.Status is not equals to Open then item Status is set to Retrospect, this is ok.
But I want another check, I want to see if this item is editable, for this I have a bool variable, edit. Naturally I wrote it like this:
ng-click="parent.Status != 'Open' && edit || (item.Status='Retrospect')"
So, I thought that if parent.Status is not equals to Open AND edit equals true my item.Status will be updated, problem is that it was updated no matter if edit was true or false (thinking it's because the first check is true, so it doesn't care about edit)
i also tried it like this, but same problem:
ng-click="(parent.Status != 'Open' && edit) || (item.Status='Retrospect')"
.. using ( )
What am I missing? Should this not be possible?
EDIT: Seems like when doing like this:
ng-click="parent.Status != 'Open' || (item.Status='Retrospect')"
item.Status will be set to 'Retrospect' if parent.Status != 'Open' resovles to false, but the problem still persist.
Also, there may be some confuison here I think, I am not checking if parent.Status != 'Open' OR item.Status='Retrospect' I am running the command item.Status='Retrospect' IF parent.Status != 'Open' equals false
My bad Okay, I am so confused right now, but my code did in fact work, the problem was my understanding of ng-click true/false evaluation and also I used != instead of !== which may have caused some issues.
I will upvote most of the answers (cause all of you were right, just not me) and accept what helped me to understand the most. Thanks all!

Such statements are called as short circuit statements.
but as per the rule for "||"
statement1 || statement2
in above, statement1 is always executed and evaluated, but statement2 is executed only if statement1 evaluates to false.
on contrary, the rule for "&&" is
statement1 && statement2
in above, statement1 is always executed and evaluated, but statement2 is executed only if statement1 evaluates to true.
check the below in console -
var parent = {};
parent.Status = "Close";
var edit = false;
var item = {};
item.Status = ""
parent.Status != 'Open' && edit || (item.Status='Retrospect');
item.Status;
the Status will be updated only when (parent.Status != 'Open' && edit) evaluates to false.
You can refer - http://sampsonblog.com/tag/short-circuit-evaluation
Hope this helps.

(item.Status='Retrospect') should be (item.Status === 'Retrospect') ...
Otherwise you are testing the return value of an assignment, which is always true... :-).
As a side note, always use type-converting equality comparison (=== for == !== for != JavaScript)... (for a quite complete and clear explanation, see here).
Update: From your comment I see you really meant what you wrote... :-)
However, in that case, I'd do:
if (!(parent.Status !== 'Open' && edit)) item.Status = 'Retrospect'
or:
item.Status = (parent.Status !== 'Open' && edit) ? item.Status : 'Retrospect'

In your || construct, item.Status will update if the first condition (parent.Status != 'Open' && edit) is false, not if it is true. Your first code should work the same way.
It may be cleaner and less confusing to write:
if (parent.Status != 'Open' && edit) {item.Status = 'Retrospect';}

I think you better expand the code in a function.
In Html:
ng-click="doThing()"
In the javascript:
doThing() {
if((parent.Status != 'Open') && edit) {
item.Status = 'Retrospect';
}
}

Simply use ternary operator like this:
ng-click="parent.Status != 'Open' && edit = true? item.Status='Retrospect' : item.Status='Somethingelse or null'"

Related

What's the logic behind the && (and) working while || (or ) doesn't in this code

var answer = prompt("are we there yet")
while(answer.indexOf("yes") === -1 && answer.indexOf("yeah") === -1 ){
var answer = prompt("are we there yet")
}
alert("yay we made it");
&& works when both parts are true, in this case, if we write yes OR yeah it will work, if we write only yes while it works, it's "false" because we didn't write yes AND yeah in the same prompt.
Well obviously i'm wrong. Why doesn't OR work when one of them just needs to be true, I would only need to write either yes or yeah for it to work.
The logic there is little wrong, when you write while statement
while(answer.indexOf("yes") === -1 && answer.indexOf("yeah") === -1 )
here while executes it's body when conditional inside is true
while(*true*) => do something
when you type for example yes in prompt, while takes false as conditional because
(true && false) => false
that means while doesn't execute it's body any more.
when you write || instead of &&
(true || false) => true so while statement continues to execute body
So the write code would be
while(answer.indexOf("yes") !== -1 || answer.indexOf("yeah") !== -1)

nested if statement in one line

if(something.food == true){
if(something.food.fruit == 'apple' || something.food.fruit == 'mango'){
//do something
}
}
this is clear where food must be true later check it's child object, but how to write this in one line? I mean with single if.
If something.food is true then it can not be an object containing fields as well. Though your current check does check for a "truthy" value, it reads quite strange (thanks for pointing this out T. J. Crowder). Instead you should just leave out the == true part.
The resulting check is:
if (something.food && (something.food.fruit == 'apple' || something.food.fruit == 'mango') {
//do something
}
That's all
if(something.food && (something.food.fruit == 'apple' || something.food.fruit == 'mango')) {
//do something
}
As a petition in the comments, I will explain that.
First we check something.food without == true because we need to check if it exists. Then wrap the rest of code into parenthesis and the expression will run ok

How do you make a javascript "if" statement with both "and" and "or"?

I'm trying to make a page where you fill in some input boxes and check a radio button, and if you complete all of it, you can click a div, and animations happen. The specific input boxes are not the only ones on the page. I'm trying to use a javascript "if" statement that has a bunch of "and"'s and an "or" in parentheses, but when I open the page, the code doesn't run. This isn't all my code, and I know the javascript and it's libraries are linked because I've been coding this site for a while, and everything has worked up until now. I checked the code in a javascript validator and it seemed fine. I'm not sure what I'm doing wrong.
$(document).ready(function(){
if ( $(".managementCompanyName").val() !== '' &&
$(".approvedBy").val() !== '' &&
$(".contractStartDate").val() !== '' &&
$(".proposalNumber").val() !== '' &&
$(!$("input[name='proposalReviewedForInvoice']:checked").val() || !$("input[id='proposalNotReviewedForInvoice']:checked").val()) ) {
//do stuff
}
});
Alternatively I have
$(document).ready(function(){
if ( $(".managementCompanyName").val() !== "" &&
$(".approvedBy").val() !== "" &&
$(".contractStartDate").val() !== "" &&
$(".proposalNumber").val() !== "" &&
$("input[name='proposalReviewedForInvoice']:checked").val() !== "" ) {
//do stuff
}
});
This code seems to work on another part of the site where there's only one input as a requirement.
Thank you if you can spot my error.
Wrap the || part in parentheses, otherwise the first operand to || is actually the last result from the last &&.
/*$*/(!$("input[name='proposalReviewedForInvoice']:checked").val() ||
!$("input[id='proposalNotReviewedForInvoice']:checked").val()) ) {
And actually it seems that you rather had them wrapped in a $(), which will always return a jQuery object, which will always be "truthy" in the condition.
for handling errors much better if you only used the "OR (||) " condition.
$(document).ready(function(){
var management = $(".managementCompanyName").val();
var approved = $(".approvedBy").val();
var contract = $(".contractStartDate").val();
var proposed_num = $(".proposalNumber").val();
var proposed_rev = $("input[name='proposalReviewedForInvoice']:checked").val();
if ( management == '' || approved == '' || contract == '' || proposed_num == ''
|| proposed_rev == '' ) {
// error message
} else {
// do stuff
}
});

Jquery string and logical OR

Whats wrong with the below lines of code ...
Its keep complaing that systax error..at the like
if( (radioval === "undefined") || (radioval === null) || (radioval === "null") ) {
complete condition in action
if($('#digitallogin').is(":checked")){
var radioval = $("input[name=certificateradio]:checked").val();//its giving the string "user"
if( (radioval === "undefined") || (radioval === null) || (radioval === "null") ) { //this line
$("#login_error").text("please select the signin certificate");
return false;
}
}
Thanks for any Assistance.
There's no syntax error in your code. If the code had a syntax error, there would be an error message in the Firebug console (not the Watch panel), and the code would not run at all. You'd never get to your breakpoint.
The syntax errors in your screenshot are in your watch expressions. Delete the watch expressions and those error messages will go away.
In your updated screenshot I can see what the syntax error is. Take a close look at your watch expression (reformatted here to avoid scrolling):
if(
(radioval === "undefined") ||
(radioval === null) ||
(radioval === "null")
)
That's not an expression, it's an if statement. If you want to use it as a watch expression, you need just the expression inside the if statement. That is, remove the if( and the final ).
Regarding the specific tests you're making, jQuery's .val() method does return undefined if there are no elements selected. Note that there is an error in the jQuery documentation: it says that .val() returns null when there are no matching elements. This is incorrect; it returns undefined in this case. Here is the line of code in the jQuery source that returns undefined (because it is a simple return; with no value).
But that is the undefined value, not the string "undefined". You would test for this with radioval === undefined. Or you could use radioval == null. Note the == instead of ===; this test matches both null and undefined values. That may be the safest bet, in case the jQuery team ever decides to change the code to match the documentation and start returning null instead of undefined. (An unlikely possibility, but you never know.) By testing radioval == null it would test against either value.
Try
if( (typeof radioval === "undefined") || (radioval === null) || (radioval == "null") ) {
in the third comparison of radioval
radioval == "null" and not === null
$("input[name=certificateradio]:checked").val(); returns undefined (typeof undefined === undefined) if it's unchecked or "on" (typeof "on" === string) if it's checked.
a small example:
<input name="certificateradio" type="checkbox" />
<button>run</button>
$("button").click(function(){
console.log($("input[name=certificateradio]:checked").val());
console.log(typeof $("input[name=certificateradio]:checked").val());
});
http://jsfiddle.net/x2uw4/1/
try to use:
if($("input[name=certificateradio]:checked").val() ==="on"){
...
}
.val() returns a string value, null or an Array in case of a multiselect value, so you could try:
if (/null|undefined/i.test(radioval) || !radioval.length){ /*...*/ }
Since you seem to check for [one of] $("input[name=certificateradio]") being checked, it may also be sufficient to do
if( ( !$("input[name=certificateradio]:checked").length ) {
$("#login_error").text("please select the signin certificate");
return false;
}
Or even shorter
if( $('#digitallogin').is(":checked") &&
!$("input[name=certificateradio]:checked").length ) {
$("#login_error").text("please select the signin certificate");
return false;
}

Ternary Operators as short conditional statements

Is there anything wrong with using ternary operators in place of longer conditional statements in Javascript, for instance using:
(variable == "dog") ? dog_stuff() : false;
Rather than
if ( variable == "dog" )
{
dog_stuff();
}
This may sound like a stupid question but I just find it's pretty quick and easy to read, I just don't want to be using it if there's a possible drawback?
You could also write
(variable == 'dog') && dog_stuff();
if you don't have an else statement.
A few lines from backbone.js:
options || (options = {});
models = _.isArray(models) ? models.slice() : [models];
model = this.getByCid(models[i]) || this.get(models[i]);
You can group multiple statements, if it's very necessary:
(1==1) && (a=2,b=3)
alert(a); // 2
alert(b); // 3
It's wrong because you're telling your code to execute false. Imagine the following code:
if ( variable == "dog" )
{
dog_stuff();
} else {
false;
}
IMO the 4 line conditional function call is perfectly fine. You can shorthand it to:
if (variable == "dog") dog_stuff();
The only problem with this is if you comment it out, or add 1 more function then things look correct, but don't execute correctly:
if (variable == "dog") dog_walk(); dog_bark(); // dog_bark executes always!
if (variable == "dog") // dog_walk();
earn_cash(); // suddenly earn_cash() is dog-dependent.
As long as the format is easily understood by you and anyone else that may need to read the code, it's fine.

Categories