Why wont my function return true? - javascript

I cant seem to get this function to return true even after ticking the two check boxes I have on the page. I've been working on this for hours now and running out of ideas. Any help would be much appreciated.
if(myfunction() == true){
alert('YAY!');
}
function myfunction(){
if($("input[type=checkbox]").length > 0){
$('.checkbox').each(function(){
if($(this).prop('checked')){
return true;
}
else{
$(this).find(".CheckboxCheck").show();
return false;
}
});
}
else{
return true;
}
}

You are returning true from within the function that you passed to each, not from myfunction. Except in the case that there are no check boxes on your page, and thus the else block executes in myfunction, myfunction is returning undefined.
You can do something like this however:
if(myfunction() == true){
alert('YAY!');
}
function myfunction(){
var returnValue = true;
if($("input[type=checkbox]").length > 0) {
$('.checkbox').each(function(){
if($(this).prop('checked')){
returnValue = true;
return false; // Stops the each loop.
}
else {
$(this).find(".CheckboxCheck").show();
returnValue = false;
return false; // Stops the each loop.
}
});
}
return returnValue;
}
Now, I'm not exactly sure of what you're trying to do, and you will almost certainly need to tweak the code above. I'm just providing it as a way to illustrate how to get a value out of the function passed to each. If you're trying to determine if all of the checkboxes are checked, for example, then you'll want your each function to look something like this:
var returnValue = true;
...
$('.checkbox').each(function() {
if (!$(this).prop('checked')) {
returnValue = false;
return false;
}
});
EDIT: After looking at the second code snippet again, I realized that the each loop is unnecessary. If you want to determine if all check boxes are checked, all you need is this:
if ($('.checkbox:not(:checked)').length == 0) {
// All .checkbox elements are checked.
}
Now, keep in mind that the :not() and :checked selectors can't utilize the native JS functions, so they are slower, but probably not enough to matter. I prefer the conciseness.

Returning from inside the each callback function will not return from the outer function. The function will return undefined as you haven't specified any return value for it, and that is not equal to true.
You can use a variable for the result, that you set from within the loop:
function myfunction(){
var result = true;
$('.checkbox').each(function(){
if(!$(this).prop('checked')){
result = false;
$(this).find(".CheckboxCheck").show();
return false; // exit the loop
}
});
return result;
}

Related

Difference between JQuery $.each loop and JS for loop [duplicate]

I want to return false and return from function if I find first blank textbox
function validate(){
$('input[type=text]').each(function(){
if($(this).val() == "")
return false;
});
}
and above code is not working for me :(
can anybody help?
You are jumping out, but from the inner loop, I would instead use a selector for your specific "no value" check, like this:
function validate(){
if($('input[type=text][value=""]').length) return false;
}
Or, set the result as you go inside the loop, and return that result from the outer loop:
function validate() {
var valid = true;
$('input[type=text]').each(function(){
if($(this).val() == "") //or a more complex check here
return valid = false;
});
return valid;
}
You can do it like this:
function validate(){
var rv = true;
$('input[type=text]').each(function(){
if($(this).val() == "") {
rv = false; // Set flag
return false; // Stop iterating
}
});
return rv;
}
That assumes you want to return true if you don't find it.
You may find that this is one of those sitautions where you don't want to use each at all:
function validate(){
var inputs = $('input[type=text]');
var index;
while (index = inputs.length - 1; index >= 0; --index) {
if (inputs[index].value == "") { // Or $(inputs[index]).val() == "" if you prefer
return false;
}
}
// (Presumably return something here, though you weren't in your example)
}
I want to add something to existing answers to clear the behavior of $(selector).each and why it doesn't respect return false in OP's code.
return keyword inside $(selector).each is used to break or continue the loop. If you use return false, it is equivalent to a break statement inside a for/while loop. Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration. Source
Because you're returning false, the loop breaks and the function ends up returning undefined in your case.
Your option is to use a var outside $.each or avoid using it altogether as #TJCrowder wrote.

Trying to solve If/else problem with specific string and boolean

Problem
I've tried multiple avenues and watched videos. I'm stuck...
function exerciseThree(typeOfPizza){
let lovesPizza;
// In this exercise, you will be given a variable, it will be called: typeOfPizza
// You are also given another variable called: lovesPizza;
// Using an if/else statement assign lovesPizza to true if typeOfPizza is 'pepperoni', assign it to false if it is 'olives'
What I've tried:
if (lovesPizza==='pepperoni') {
// The value is empty.
return true;
}
else {
(lovesPizza==='olives')
return false;
}
Another attempt
// if(lovesPizza===pepperoni){
// return true
//}
//else (lovesPizza===olives){
// return false
// }
Another one
//if (lovesPizza.equals(pepperoni))
// return "true";
//else (lovesPizza.equals(olives))
// return "false"
As the comments say, you're looking for if / else. You should also double check your reading of the question, you had your checking / assigning variables the wrong way around
function exerciseThree(typeOfPizza){
let lovesPizza;
if (typeOfPizza === 'pepperoni') {
lovesPizza = true;
} else if (typeOfPizza === 'olives') {
lovesPizza = false;
}
console.log('lovesPizza:', lovesPizza);
};
exerciseThree('pepperoni');
exerciseThree('olives');
I would highly recommend using a switch statement in this case here. Switch statements run faster and are easier to work with in my opinion.
But to point out what you're doing wrong:
Here you are checking if lovesPizza has the value of pepperoni. But you should be checking typeOfPizza. This is why you're most likely getting undefined:
if (lovesPizza==='pepperoni') {
// The value is empty.
return true;
}
else {
(lovesPizza==='olives')
return false;
}
Check out how this looks with a switch statement.
function exerciseThree(typeOfPizza) {
switch (typeOfPizza) {
case 'pepperoni':
return true;
case 'olives':
return false;
default:
return false;
}
}
exerciseThree('pepperoni');
exerciseThree('olives');
Your else statement needs an if
if(somethingisTrue)
{
return "it is true";
}
else if(somethingelseistrue)
{
return "no the other thing was true";
}
else
{
return "nothing is true"
}
Also === checks the strings equal and are both strings. It is often better to make sure the if is case insensative
if(!typeOfPizza)
{
//raise an error as null was passed in
return "false"
}
else if(typeOfPizza.toLowerCase().trim()==="pepperoni"){
{
return true..... you can build the rest
I often write a function (prototype) called cleanString or compareString to perform all the normal cleaning up of strings.
A simple solution is but doesn't use ifs as asked.
function exerciseThree(typeOfPizza){
let lovesPizza= typeOfPizza==="pepperoni";
return lovesPizza;
}
I certainly hope you teacher is playing a trick on you.
There is no sane suggestions what to do if you send for instance 'ham' into it, and not handle all possibilities are just sloppy.
let lovesPizza;
function exerciseThree(typeOfPizza){
if(typeOfPizza === 'pepperoni') {
return true;
} else if (typeOfPizza === 'olives') {
return false;
} else {
return undefined;
}
}
lovesPizza = exerciseThree('pepperoni');
console.log(lovesPizza); // true
lovesPizza = exerciseThree('olives');
console.log(lovesPizza); // false
lovesPizza = exerciseThree('ham');
console.log(lovesPizza); // undefined

how to return or exit from the $scope function in angular js

In certain condition, I want to exit from my $scope function.I am trying this using return. But no luck it returns only from each loop, not from the main scope function. In my code, even d.xyz is true f2 function is getting called. I want to exit from f1 if xyz of d gets true.
$scope.f1 = function(){
angular.foreach(data, function(d){
if(d.xyz){
return; // tried with return false also
}
if(d.abc){
//some code
}
$scope.f2();
})
}
You can't really exit from angular's forEach function. The best you can do, is make sure the callback is returned every iteration after your exit condition is true.
So you would do it like this:
$scope.f1 = function(){
var stopRunning = false;
angular.foreach(data, function(d){
if(stopRunning){
return;
}
if(d.xyz){
stopRunning = true;
return;
}
if(d.abc){
//some code
}
$scope.f2();
})
}
angular.module("test",[]).controller("testC",function($scope){
$scope.data = [{"test":1},{"test":2}];
$scope.IsExist=false;
$scope.testF=function() {
for(var i=0;i<$scope.data.length;i++){
if($scope.data[i].test==1){
alert(1);
$scope.IsExist=true;
}else if($scope.data[i].test){
}
if($scope.IsExist)
{
return false;
}
$scope.testF();
}
}
$scope.testF();
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="test" ng-controller="testC">
</div>
$scope.f1 = function(x = true){
angular.foreach(data, function(d){
if(d.xyz){
x = false;
return; // tried with return false also
}
if(d.abc){
//some code
}
$scope.f2();
})
if (!x){
return;
}
}
Basically you are not exiting f1(). This will do that for you.
You should use return statement in your function. It is not exiting as you are using return in angular.foreach callback function. Try using outside.
I think You should use break;. if You are using return; this works like a continue;

Javascript function returning undefined for template helper

Creating a template helper to return a variable to be displayed in the DOM, and my function is returning undefined and thus is not affecting the DOM. Not exactly sure why, though I feel as if it is a binding issue. Here's the code:
supportNumber: function(){
var jobSupportNumber = state.user.jobs.each(function(job){
console.log(jobOrder.get("jobId"));
console.log("test");
console.log(job.get("id"));
if(jobOrder.get("jobId") == job.get("id")){
var jobNumber = job.get("supportNumber");
console.log(jobNumber);
return jobNumber;
}
else{
console.log("this fired");
}
});
console.log(jobSupportNumber);
return jobSupportNumber;
}
I'm console logging alot to make sure values are being returned, and something is being returned all the way up until the final return statement, which returns jobSupportNumber as undefined. What am I doing wrong to have it return always as undefined?
.each() doesn't return the value of any of the function it's wrapping. The inner function results are only used to control the .each() loop.
Try this:
supportNumber: function(){
var jobSupportNumber = null;
state.user.jobs.each(function(job){
if(jobOrder.get("jobId") == job.get("id")){
jobSupportNumber = job.get("supportNumber");
return false; // tell .each() to quit looping
}
});
return jobSupportNumber;
}
By the code you have there, state.user.jobs.each() is not going to return jobNumber. That return applies to your anonymous function. (where you have function(job).
To get that value, you want something more like this:
supportNumber: function(){
var jobSupportNumber;
state.user.jobs.each(function(job){
console.log(jobOrder.get("jobId"));
console.log("test");
console.log(job.get("id"));
if(jobOrder.get("jobId") == job.get("id")){
var jobNumber = job.get("supportNumber");
console.log(jobNumber);
/* Set the value and just plain return, instead */
jobSupportNumber = jobNumber;
return;
}
else{
console.log("this fired");
}
});
console.log(jobSupportNumber);
return jobSupportNumber;
}

Avoid execution goes on in a .each loop

I've got a code like this one to see whether some radio buttons have been checked or not. I'm using .each function of jquery to show an alert when I find a group of radio buttons with the same name value and none of them have been checked. When I find one I want to fire an alert and return false, but after the alert is shown the execution of the .each stops but the lines after .each function are executed (I mean true value is executed).
$(":radio").each(function(){
var name = $(this).attr('name');
var numAnswered = $(":radio").filter('[name='+name+']').filter(":checked").length;
var notAnswered = numAnswered == 0;
if(notAnswered){
alert("Must answer all questions");
return false;
}
});
console.log('still goes here even when alert is fired');
return true;
How can I avoid this situation?
Thanks.
var myreturnvalue = true;
$(":radio").each(function(){
var name = $(this).attr('name');
var numAnswered = $(":radio").filter('[name='+name+']').filter(":checked").length;
var notAnswered = numAnswered == 0;
if(notAnswered){
alert("Must answer all questions");
myreturnvalue = false;
return false;
}
});
console.log('still goes here even when alert is fired');
return myreturnvalue;
You can use that same notAnswered variable (or another, whatever floats your boat) at a higher scope, like this:
var notAnswered;
$(":radio").each(function(){
notAnswered = $(":radio[name="+this.name+"]:checked").length == 0;
if(notAnswered){
alert("Must answer all questions");
return false;
}
});
if(notAnswered) return false;
console.log("will only fire if there's an answer");
return true;
The other changes above are just slimming down the code, you can get away with far fewer selector engine invocations :)

Categories

Resources