复选框:使用按钮开/关

checkbox : on/off using button

本文关键字:按钮 复选框      更新时间:2023-09-26

有一个复选框&按钮,我想点击按钮选中&未选中复选框而未触及该复选框。怎么做?

<input type = "checkbox"  id = "check" />
<input type = "button"  id = "buttonId" />
<script type = "text/javascript">
   $(function() {
       $("#buttonId").click( function() { 
            if( $("#check").is_NOT_CHECKED) {
                 CHECKED_CheckBox;
                        }         else 
                     if($("#check").is_CHECKED) {
                           UnCHECKED_CheckBox;
                           }    
                    });
   </script>
$("#buttonId").click( function() {
    // or .attr() prior to jQuery 1.6
    $("#check").prop('checked', function(i, val) {
        return !val;
    });
});

根据上下文,您还可以利用这样一个事实,即单击复选框的label将切换其状态:

<input type="checkbox" id="check" name="check"/> 
<label for="check">Some text</label>

$("#buttonId").click( function() {
    var checkbox = $("#check")[0];
    checkbox.checked = !checkbox.checked; // invert its checked status
});

demo at http://jsfiddle.net/gaby/czRkv/

假设这些是你的复选框和按钮:

<input id="checkbox_id" type="checkbox" /><br>
<input id="button_id" type="button" value="Change" />​

然后你可以使用下面的代码来执行复选框的打开/关闭:

​$("#button_id").click(function() {
    // if the checkbox is not checked
    if (! $("#checkbox_id").is(":checked")) {
        $("#checkbox_id").prop("checked", true);
    } else { // if the checkbox is checked
        $("#checkbox_id").prop("checked", false);        
    }
});​

查看这个实时演示:http://jsfiddle.net/kvRG4/