简体   繁体   中英

checkbox : on/off using button

There is a CheckBox & Button, I want to click on Button to checked & unchecked the checkBox without touching the checkBox. How to do that ???

<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;
    });
});

Depending on the context, you could also make use of the fact, that clicking on the label of a checkbox toggles its status:

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

Works without JavaScript :)

How about

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

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

});

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

Say these are your checkbox and button:

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

Then you can perform checkbox on/off using this code:

​$("#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);        
    }
});​

See this live demo: http://jsfiddle.net/kvRG4/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM