当用户单击按钮时,如何选择所有复选框

leo*_*ora 1 jquery

我有一个带有"全选"按钮和一堆复选框的表单.我希望在用户单击"全选"按钮时选中所有复选框.

在jquery中有优雅的方法吗?

编辑#2:我已将问题分解为此代码; style ="display:none;".如果我删除此代码它工作正常.有任何想法吗?

编辑:下面的答案在我的测试表单中工作,但在这种情况下按钮是在div内部的一个表单内部,只显示为simpledialog.show()的一部分.在这种情况下,由于某些原因,当我点击按钮时,我没有看到任何事情发生:

JavaScript的:

<script type="text/javascript">
$(document).ready(function() {
    $('#sdHc3').simpleDialog({
        showCloseLabel: false,
        open: function() {
            $('#checkboxStatus').html('');
        },
        close: function() {
            var c = [];
            $('#checkboxForm :checkbox:checked').each(function() {
                c.push($(this).val());
            });
            $('#checkboxStatus').html('&nbsp;&nbsp;Checked <b>' + c.join(', ') + '</b>.').show();
        }
    });

});
Run Code Online (Sandbox Code Playgroud)

<script type="text/javascript">
$(function() {
$('#selectAll').click(function() {
        var select_all = (this.value === 'Select All');
        $(':checkbox').attr('checked', select_all);
        this.value = (select_all) ? 'Deselect All' : 'Select All';
    });
});
Run Code Online (Sandbox Code Playgroud)

身体:

<div style="display: none;" class="scrollableDiv" id="simpleDialog3">
    <h3>DEMO3</h3>
    <form id="checkboxForm">
    <input type="button" id="selectAll" value="TT" />
    <input type="checkbox" class="chckbx" value="1" /><br />
    <input type="checkbox" class="chckbx" value="1" /><br />
    </form>
    <p>
        <a href="#" class="close">Close</a></p>
</div>
Run Code Online (Sandbox Code Playgroud)

知道为什么在这种情况下它不起作用?

Cha*_*ion 6

$(function(){
    $('#myButton').click(function(){
        var select_all = (this.value === 'Select All');
        $('input:checkbox').attr('checked', select_all);
        this.value = (select_all) ? 'Deselect All' : 'Select All';        
    });
});
Run Code Online (Sandbox Code Playgroud)

尝试在对话框实例化之前放置此代码.

看起来你可能想切换到jQuery UI Dialog.