Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
605 views
in Technique[技术] by (71.8m points)

javascript - Check if a checkbox is checked in a group of checkboxes in clientside

Please note that the scenario is ASP.NET Webforms + Master - Content page which mess up the ids.
I have, say, three checkboxes

<asp:CheckBox ID="chkConsultantQuality" runat="server" 
            CssClass="company"/>
<asp:CheckBox ID="chkConsultantEnvironment" runat="server" 
            CssClass="company"/>
<asp:CheckBox ID="chkConsultantSafety" runat="server" 
            CssClass="company"/>

I would like to make a div id="CompanyPanel" on click event of each checkbox according to the following condition

  1. visible if any of the checkboxes are checked.
  2. hidden if all of the checkboxes are unchecked.

I am planning to use jQuery since I am selecting by class name. I could do it with jQuery.each on the class='company' by checking each for a checked flag.
Any better ideas?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There is a :checked ( http://api.jquery.com/checked-selector/ ) selector you can use :

<script>
    $(document).ready(function() {
        $(".company input").click(function() {
            var cnt = $(".company input:checked").length;

            if( cnt == 0)
            {
               // none checked
               $('#CompanyPanel').hide();
            }
            else
            {
               // any checked
               $('#CompanyPanel').show();
            }
        });
    });
</script>

You may want to add (or use) an id on the container of these checkbox, to optimize selector speed.

As for asp.net messing up client ids on controls, you can use

$('<% =MyControl.ClientID %>')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...