javascript - checkbox : onoff using button - Stack Overflow

admin2025-04-18  0

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>

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>
Share asked Jul 27, 2011 at 10:58 user744587user744587 1
  • Similar to stackoverflow./questions/426258/… ? – anothershrubery Commented Jul 27, 2011 at 11:00
Add a ment  | 

3 Answers 3

Reset to default 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 :)

How about

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

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

});

demo at http://jsfiddle/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/kvRG4/

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1744931265a275171.html

最新回复(0)