复选框:使用按钮开/关

3
有一个复选框和按钮,我想通过点击按钮来选中或取消选中复选框,而不需要触碰复选框。如何做到这一点?
<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>

类似于 https://dev59.com/N3RC5IYBdhLWcg3wD8tV ? - anothershrubery
3个回答

6
$("#buttonId").click( function() {
    // or .attr() prior to jQuery 1.6
    $("#check").prop('checked', function(i, val) {
        return !val;
    });
});

根据上下文,您还可以利用以下事实:单击复选框的会切换其状态:

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

无需 JavaScript 即可使用 :)


不错...使用jQuery v1.6中添加的.prop(propertyName, function(index, oldPropertyValue))覆盖。 (http://api.jquery.com/prop/) - Dunc

2

关于这个问题

$("#buttonId").click( function() {
    var checkbox = $("#check")[0];

    checkbox.checked = !checkbox.checked; // invert its checked status

});

请参考 http://jsfiddle.net/gaby/czRkv/ 中的演示。


0

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

<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/


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接