I am trying to validate elements inside a javascript function which contains two jQuery callback loops. Based on the conditions I want to return true
/false
from the inner jQuery loop and that should be sent back to the calling method of javascript. If the result of the inner loop is true
the loop should stop running.
if(validate(key)){
}
else{
}
function validate(key) {
$jquery.each(function(){
$jquery.each(function(){
if(){
return true;
}
else{
return false}
})
})
}
I am trying to validate elements inside a javascript function which contains two jQuery callback loops. Based on the conditions I want to return true
/false
from the inner jQuery loop and that should be sent back to the calling method of javascript. If the result of the inner loop is true
the loop should stop running.
if(validate(key)){
}
else{
}
function validate(key) {
$jquery.each(function(){
$jquery.each(function(){
if(){
return true;
}
else{
return false}
})
})
}
Share
Improve this question
edited Aug 9, 2013 at 6:53
Brett DeWoody
62.9k31 gold badges144 silver badges192 bronze badges
asked Aug 9, 2013 at 6:27
Paul PhoenixPaul Phoenix
1,4336 gold badges20 silver badges34 bronze badges
0
4 Answers
Reset to default 5I think this is what you're looking for, this will stop both loops when the true
condition is met
function validate(key) {
var result = false;
$jquery.each(function(){
$jquery.each(function(){
if(){
result = true;
return false;//break inner loop
}
});
if(result)
return false; //break outer loop if we got true in inner
});
return result;
}
Demo fiddle You can open your console and see that the loop stops when the true condition is met
The jQuery docs give a similar example. The docs state 'you can stop the loop from within the callback function by returning false.'
So it sounds like you need to reverse you're terminology and return false when you want the loop to stop.
Let's say we have a bunch of div
elements with li
elements nested inside. If we wanted to stop the inner loop when it reaches an li
with specific content we could do this:
$( "div").each(function ( index, domEle) {
$( "li", domEle ).each(function ( index, domEle2) {
var areWeDone;
$( domEle2 ).css( "backgroundColor", "yellow" );
if ( $( domEle2 ).is(":contains('Here')") ) {
result = true;
return false;
} else {
result = false;
return true;
}
});
if (result == true) {
return false;
}
});
Here's the full jsFiddle.
function validate(key) {
var result;
$jquery.each(function() {
$jquery.each(function() {
if () {
result = true;
} else{
result = false
}
return false;
});
if (typeof result !== 'undefined') {
return false;
}
});
return result;
}
function validate(key) {
var result;
$jquery.each(function() {
$jquery.each(function() {
if () {
result = true;
} else{
result = false;
}
return result;
});
});
}