选中和取消选中所有复选框

时间:2012-10-10 07:38:03

标签: java javascript jquery

我无法实现这些东西,在这个页面中我想做三件事:

1> 默认情况下,将在此页面中检查Apple和Cat。  2 - ; 对于Startall,将检查并禁用所有功能。  3 GT; 对于Stopall,所有功能都将被禁用,默认(AC)值将被禁用。*

 <script type="text/javascript"> //This jquery is using for on selecting the checkbox,it will assign the text field of policyName and features
    $(document).ready(function() { 
        $('.check').click(function(){
            $("#policyName").val('Start'); 
            $("#features").val('');
                    $(".check").each(function(){
                if($(this).prop('checked')){
                    $("#policyName").val($("#policyName").val() + $(this).val());   
                    $("#features").val($("#features").val() + $(this).data('name'));
                    }           
            });
         });
    });
    </script>

这是我的jsp页面:

<div align="center" id="checkboxes">
<input type="checkbox" name="startall" data-name="Startall" class="check" id="check" value="all"> All &nbsp;&nbsp;&nbsp;
<input type="checkbox" name="stopall" data-name="Stopall" class="check" id="check" value="stopall"> STOPall &nbsp;&nbsp;
<input type="checkbox" name="apple" data-name="Apple" class="check" id="check" value="a"> Apple &nbsp;&nbsp;&nbsp;
<input type="checkbox" name="ball" data-name="Ball" disabled="disabled" checked="checked"  id="check" value="b"> Ball 
    &nbsp;&nbsp;&nbsp;
<input type="checkbox" name="cat" data-name="Cat" class="check" id="check" value="a"> Cat &nbsp;&nbsp;&nbsp;
<input type="checkbox" name="dog" data-name="Dog" checked="checked" disabled="disabled"  id="check" value="d"> Dog 
    &nbsp;&nbsp;&nbsp;
<input type="checkbox" name="elephant" data-name="Elephant" disabled="disabled" checked="checked"  id="check" value="e"> 
    Elephant &nbsp;&nbsp;&nbsp;
</div>

任何援助......都将被确认。

1 个答案:

答案 0 :(得分:1)

试试这个

HTML中的 ID 唯一 ..请尝试使用不同的ID或类。我使用name属性编写代码,这是一个慢速选择器。

$(document).ready(function() {
$('[name="apple"], [name="cat"]').prop('checked', true);

$('[name="startall"]').on('click', function() {
    var $checkboxes = $('input[type="checkbox"]').not('[name="startall"], [name="stopall"]');
    if (this.checked) {
        $checkboxes.prop({
            checked: true,
            disabled: false
        });
        $('#textbox').val( $(this).attr('data-name'));
    }
    else{
         $checkboxes.prop({
            checked: false
        });
         $('#textbox').val('');
    }
});

$('[name="stopall"]').on('click', function() {
    var $checkboxes = $('input[type="checkbox"]').not('[name="startall"], [name="stopall"]');
    if (this.checked) {
        $checkboxes.prop({
            checked: false,
            disabled: true
        });
        $('#textbox').val( $(this).attr('data-name'));
    }
    else{
         $checkboxes.prop({
            disabled: false
        });
        $('#textbox').val('');
    }
});

});

<强> UPDATED DEMO