I know you are supposed to be able to break out of an each statement by returning, which is what I'm trying to do, but I must be doing something wrong and it seems so simple I can't find it.
I have code like this
function create() {
var test = hasThing();
if (test) {
$('#myForm').submit();
} else {
alert('you suck!')
}
}
function hasThing() {
$('.selects').each(function() {
if (this.value != "") {
return true;
}
});
return false;
}
I have set breakpoints on "return true;" and hit it but var test is always false because for some reason the .each() loop continues and the hasThing() function continues. I've tried switching things around so that I return false in the .each() just in case for some reason that mattered but it didn't change anything.
I don't get it. Seems counter to how the documentation says it should work.
No, you don't need break after return, technically anything after return is unreachable code.
A return statement ends the execution of a function, and returns control to the calling function. Execution resumes in the calling function at the point immediately following the call.
Definition and UsageThe return statement stops the execution of a function and returns a value.
Return is used to immediately stop execution of a function and return a value back to where it was called from. This means it will break all loops contained in the current function call. If you want to break out of a single loop you need to use the break statement instead.
Your return true;
statement returns from the anonymous function given to each
. The return false;
line is always executed which explains why var test
is always false.
Change your code to
function hasThing() {
var hasThing = false;
$('.selects').each(function() {
if (this.value != "") {
hasThing = true;
return false; // breaks the $.each, but does not return from hasThing()
}
});
return hasThing;
}
You could use Array.some()
to check if any of the selects have a selected value
function hasThing() {
return $('select').toArray().some(function(el) {
return el.value != "";
})
}
function create() {
var test = hasThing();
if (test) {
alert('at least one select was changed');
//$('#myForm').submit();
} else {
alert('you suck!');
}
}
function hasThing() {
return $('select').toArray().some(function(el) {
return el.value != "";
})
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Select at least one option !</p>
<form id="myForm">
<select class="selects">
<option value="">blank</option>
<option value="2">option1</option>
</select>
<select class="selects">
<option value="">blank</option>
<option value="2">option1</option>
</select>
<input type="button" onclick="create()" value="submit" />
</form>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With