trex trex - 7 months ago 10
Javascript Question

Any of the inner element is visible jQuery

Is there any other quick way to achieve following functionality using jQuery.

My scenario in form validation is as follows:


  • If the error occurs in the form then, show the error message for the field in an
    li
    inside
    #errorList
    .

  • If user makes a correction then hide the li that matches error corrected

  • If the error comes (because of calculations on the page) again, then display the same error.

  • And on/before submit, I need to check if any all of the error messages are hidden. if so then only submit the form.



HTML:

<ul id="errorList" class="errorlist" style="display: inline-block;">
<li style="display: none;">不正な日付です</li>
<li class="">16 文字以内にしてください</li>
<li style="display: none;">不正な日付です</li>
<li style="display: none;">不正な日付です</li>
</ul>


js:

function has_any_visible_errors(){
var innerHiddens = [];
$("#errorList li").each(function(){
if($(this).is(":not(':visible')")){
innerHiddens.push(true);
}else{
innerHiddens.push(false);
}
});
return (innerHiddens.indexOf(false) == -1)?true:false;
}

Answer

Try this : You can make use of :visible to find visible li elements and check the number of visible lis, if it is greater than 0 then return true.

function has_any_visible_errors(){  
    return $("#errorList li:visible").length > 0;
}