3

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>

3 Answers3

6
$("#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 :)

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • Nice... uses .prop(propertyName, function(index, oldPropertyValue)) override added in jQuery v1.6 (http://api.jquery.com/prop/) – Dunc Sep 18 '11 at 10:17
2

How about

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

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

});

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

Gabriele Petrioli
  • 191,379
  • 34
  • 261
  • 317
0

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/

Amr
  • 4,809
  • 6
  • 46
  • 60