0

I need to hide a few things when a checkbox is checked, and show them when checkbox is unchecked. I use a class selector to go through the documents and hide these elements.

The code seems to work, the only problem is each time the page is loaded, when I check it, the change event does not fire. I have to un-check, then check again, then the event fires. Please help me see what I did wrong.

        <script type="text/javascript">
            $(document).ready(function () {
                $('#chkFiles').change(function () {
                    if (this.checked)
                        $(".hideWhenChecked").hide();
                    else
                        $(".hideWhenChecked").show();
                });
            });
    </script>

The elements to be hidden are like this:

    <TR>
        <TD style="WIDTH: 144px" width="144"><span class="hideWhenChecked">Select:</span></TD>
        <TD><span class="hideWhenChecked"><asp:dropdownlist id="ddl" runat="server" AutoPostBack="True"></asp:dropdownlist></span></TD>
</TR>

Our jquery library is 1.4.1, it's old, but it's not up to me to make the decision to update it. Some functionality are not available in this version.

4

1 回答 1

0

您需要在页面加载时检查更改内执行您的逻辑,以便您可以.hideWhenChecked根据chkFiles来自服务器的方式隐藏。

<script type="text/javascript">
    $(document).ready(function () {
        onChkChanged(); // <-- execute on page load

        $('#chkFiles').change(function () {
            onChkChanged(); // <-- execute on checked changed
        });
    });

    function onChkChanged() {
        var show = $('#chkFiles').is(':not(:checked)');
        $(".hideWhenChecked").toggle(show);
    }
</script>
于 2013-06-13T19:38:28.710 回答