开发者

Avoid execution goes on in a .each loop

开发者 https://www.devze.com 2023-01-27 11:17 出处:网络
I\'ve got a code like this one to see whether some radio buttons have been 开发者_JAVA技巧checked or not. I\'m using .each function of jquery to show an alert when I find a group of radio buttons with

I've got a code like this one to see whether some radio buttons have been 开发者_JAVA技巧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 :)

0

精彩评论

暂无评论...
验证码 换一张
取 消