I neeed help with multiple if conditions.
if condition 1 & condition 2 true means I want both condition actions:
if(condition 1 true) {
$('.inner_wrapper').addClass('em-border-red');
return false;
}
if(condition 2 true) {
$('.cCal').addClass('em-border-red');
return false;
}
if(condition 3 true){
$('.cCal-row2').addClass('em-border-red');
return false;
}
But only one condition works.
Each of your if blocks contains a return statement. As soon as one condition is met, no further code will execute. This is, by definition, the behaviour of the return statement:
A return statement causes a function to cease execution and return a value to the caller
Since all of yours just return false, you should be able to move the return to after the conditions:
if(condition1) {
$('.inner_wrapper').addClass('em-border-red');
}
if(condition2) {
$('.cCal').addClass('em-border-red');
}
if(condition3) {
$('.cCal-row2').addClass('em-border-red');
}
return false;
Remove the return false; form each if block and try to manage it at the bottom, outside of if condition.
retVal = true;
if(condition 1 true)
{
$('.inner_wrapper').addClass('em-border-red');
retVal = false;
}
if(condition 2 true)
{
$('.cCal').addClass('em-border-red');
retVal = false;
}
if(condition 3 true)
{
$('.cCal-row2').addClass('em-border-red');
retVal = false;
}
return retVal;
You have two ways:
<!-- and condition //-->
if (a == b && a != c) {
// your stuff
<!-- or condition //-->
} else if (a == c || a ==b) {
// other stuff
<!-- otherwise //-->
} else {
// another stuff
}
Otherwise you have "switch case". Like on this page.
Related
I want to loop through something, and return true if at any point of loop, condition is met. If not met at all, then want to return false. How do I do this in Javascript.
Cant just write if and else, because only want the else to take care after finish looping all the options...
You can just do:
if(condition){
return true;
}
return false;
If I understand correctly, you're saying that you can't use else because you want to test all conditions, even if multiple of them are true?
If so, then you can use a variable to keep track of your return value, and then just return it at the end:
var result = false;
if (condition1) {
// ... whatever other logic you have ...
result = true;
}
if (condition2) {
// ... whatever other logic you have ...
result = true;
}
// ... etc. ...
return result;
Yes it can be done, return true when the condition is met and return false when the for loop has finished looping. Here is an example :
function my_function(array) {
for (var i = 0; i < array.length; i++) {
if (array[i] == 'my_test') {
return true;
}
}
return false;
}
if (x) { */ Do stuff and then eventually */ return true; }
if (y) { */ Do stuff and then eventually */ return true; }
if (z) { */ Do stuff and then eventually */ return true; }
...
return false;
If and only if none of the ifs are triggered, it will return false. If any of the ifs are triggered, it will return true within the if
I'm trying to write a function that checks whether a value is odd or even, but it isn't quite working as it should, or rather, at all.
The code I got was from this question.
function isEven(value) {
if (value % 2 == 0) {
return true;
console.log("True");
}
else {
return false;
console.log("False");
}
console.log(value);
}
isEven(3);
I get no errors in the browser's console, but it also does not log True, False, or value.
Note: I will also accept jQuery solutions, but would prefer Javascript.
You are returning before logging. Anything after return will not be executed.
return after logging
function isEven(value) {
if (value % 2 == 0) {
console.log("True");
return true;
} else {
console.log("False");
return false;
}
}
isEven(3);
Ensure value is an integer first by parsing it with
parseInt(value)
I'm reviewing some code where the logic looks flawed. I'm not sure if the following code will ever return false because of the if else return flow. My question is, will the following code ever return false, or even throw an error?
function performSearch(e) {
if(e.keyCode === RETURN_KEY_KEYCODE) {
var select = document.getElementById("selectmenusearch");
var selected = select.options[select.selectedIndex].value;
if(selected === 'organisation') {
submitSearchForm('<%= doOrganisationSearchURL %>');
} else {
submitSearchForm('<%= doIndividualSearchURL %>');
}
} else {
return false;
}
return true;
}
So the flow to me looks like
if (this condition is true) {
//execute some code
} else {
return false
}
else return true
NB: I know it would be better to refactor to have only one return statement but it looks to me like there are two else statements.
It depend of e.keyCode but if e.keyCode is not always equal to RETURN_KEY_CODE it will not always return false. You have 2 return. The first one is in the else of the first if so if e.keyCode !== RETURN_KEY_CODE, false is return. Else, you if will end normally and the instruction after it is return true.
function performSearch(e) {
if(e.keyCode === RETURN_KEY_KEYCODE) {
...
} else {
return false; // RETURN_KEY_KEYCODE !== e.keyCode
}
return true; // RETURN_KEY_KEYCODE === e.keyCode
}
I don't see any wait it can alway return false if e.keyCode is not always the same value. :)
If you want to make it more clear, you can just put the return in the end of the first if. Like that:
function performSearch(e) {
if(e.keyCode === RETURN_KEY_KEYCODE) {
...
return true; // RETURN_KEY_KEYCODE === e.keyCode
} else {
return false; // RETURN_KEY_KEYCODE !== e.keyCode
}
}
Just run a test. Seems like you were confused with what happens when there is more than one "return" statement in a function.
A return statement is a regular statement, just like any other - except for the fact that it will interrupt the local block execution and return flow control to the code that called the function. It is indifferent for you the fact that you have one, two, three returns... the language interpreter strictly follows the IF/ELSE rules - if a condition is met, then the block (delimited with "{ }" defined immediately under the if is the one that is executed, if the condition is not met, then the respective if's else block is executed. Whatever is the case, both if and else blocks, upon reaching their ends, will return flow to the next statement right after the if block (the if block is comprised by the if + else blocks), in the example here, "return true".
(function() {
if (k) {
console('k renders true');
}
else {
console.log('else reached');
return false;
}
return true;
console.log('bottom return true reached');
})();
I have the following:
var detail = 'two';
function chkDetail(detail){
if(detail == 'one') {
jQuery('#valMsg').text('one');
}
if(detail == 'two') {
jQuery('#valMsg').text('two');
}
if(detail == 'three') {
jQuery('#valMsg').text('three');
}
else {
jQuery('#valMsg').text('NO');
}
}
Depending on what string is passed into my function, I want the appropriate message to be passed into my valMsg div.
In the above scenario, my function keeps returning NO.
Can anyone tell me why this is?
Are the if statements incorrect?
Should add else on all statements:
function chkDetail(detail){
if(detail == 'one') {
jQuery('#valMsg').text('one');
}
else if(detail == 'two') {
jQuery('#valMsg').text('two');
}
else if(detail == 'three') {
jQuery('#valMsg').text('three');
}
else {
jQuery('#valMsg').text('NO');
}
}
You've separated the conditions. I'll add spacing to illustrate:
// first condition
if(detail == 'one') {
jQuery('#valMsg').text('one');
}
// second condition
if(detail == 'two') {
jQuery('#valMsg').text('two');
}
// third condition
if(detail == 'three') {
jQuery('#valMsg').text('three');
}
else {
jQuery('#valMsg').text('NO');
}
So if, for example, detail is "one" then:
First condition enters the if block
Second condition does not enter the if block
Third condition does not enter the if block, does enter the else block (since else is the logical inverse of if)
If they should all be the same condition, use else if blocks:
// all one condition
if(detail == 'one') {
jQuery('#valMsg').text('one');
}
else if(detail == 'two') {
jQuery('#valMsg').text('two');
}
else if(detail == 'three') {
jQuery('#valMsg').text('three');
}
else {
jQuery('#valMsg').text('NO');
}
This way as soon as one block is entered, the rest are skipped because the condition as a whole has been satisfied.
The else is referring to the previous if only, not to all of the if statements.
The answers supplied here do not check on the datatype, what could be crucial for the check.
var int1 = 1
var string1 = '1'
if(string1 == int1) would return true but they are actually not the same.
I would use the switch statement that is better looking code and does also check on datatype.
var detail = 'two';
function chkDetail(detail){
switch(detail){
case 'one' : jQuery('#valMsg').text('one'),
case 'two' : jQuery('#valMsg').text('two'),
default : jQuery('#valMsg').text('No')
}
If you want to go the route of the multiple if statements, then please use the === operator to make sure there is a check on datatype as well. This will prevent a lot of sketchy behaviour and bugs.
if(detail === 'one') {
jQuery('#valMsg').text('one');
}
if(detail === 'two') {
jQuery('#valMsg').text('two');
}
if(detail === 'three') {
jQuery('#valMsg').text('three');
}
else {
jQuery('#valMsg').text('NO');
}
}
Take a look at this and this for more information.
I have my JavaScript code as:
$('[id^="thresholdParameter_"]').each(function(i, value) {
//any field is edited
if($(this).val() !== previousThresholdParameters[i]){
alert('Hello');
return true;
}
});
Here I want that once it reaches return true; it must come out of the function and return the true value. However, it it keeps on iterarting.
Why is it so? return in JavaScript does not function like return in Java??
Use return false instead of return true, as return true treated as continue and return false as break in $.each loop,
$('[id^="thresholdParameter_"]').each(function(i, value) {
//any field is edited
if($(this).val() !== previousThresholdParameters[i]){
alert('Hello');
return false; // use false
}
});
From $.each()
We can break the $.each() loop at a particular iteration by making the
callback function return false. Returning non-false is the same as a
continue statement in a for loop; it will skip immediately to the next
iteration.
Return false in each callback will only stop the each function.
See last example from jQuery each API: http://api.jquery.com/each/
You can try this:
var conditionMet = false;
$(selector).each(function() {
if (innerConditionMet) {
conditionMet = true;
return false; // stop the each
}
});
Try this since in your case it looks like you want to return true and used somewhere else:
var flag = false;
$('[id^="thresholdParameter_"]').each(function(i, value) {
//any field is edited
if($(this).val() !== previousThresholdParameters[i]){
alert('Hello');
flag = true;
return false;
}
});
var x = $('[id^="thresholdParameter_"]');
for(i in x){
if(x[i] !== previousThresholdParameters[i]){
alert('Hello');
return true; //
break;
}
}
retun false to break out of $.each()
try this fiddle for better understanding: http://jsfiddle.net/patelmilanb1/q348g/
<div class="number">
<h1>1</h1>
<h1>2</h1>
<h1>3</h1>
<h1>4</h1>
<h1>5</h1>
<h1>6</h1>
<h1>7</h1>
</div>
$('.number h1').each(function () {
var h1Value = $(this).text();
if (h1Value == 5) {
return false;
} else {
$(this).css("background-color", "#F1F1EF");
}
});
it will add background colour to all h1 untill it reaches number 5 and then breaks out of $.each loop