checkbox jquery or javascript oncheck?

后端 未结 3 829
攒了一身酷
攒了一身酷 2020-12-31 02:27

I do not know the correct terminology for this, but I want the same effect as onclick but for a check box with jquery or javascript.

onclick version:



        
相关标签:
3条回答
  • 2020-12-31 03:02
    $('#input_id').click(function() {
        // do what you want here...
    });
    
    0 讨论(0)
  • 2020-12-31 03:09

    You should listen to the change event, as the checkbox can be selected or deselect with the keyboard too:

    $('input[type="checkbox"][name="change"]').change(function() {
         if(this.checked) {
             // do something when checked
         }
     });
    

    Similarly with plain JavaScript:

    // checkbox is a reference to the element
    
    checkbox.onchange = function() {
         if(this.checked) {
             // do something when checked
         }
    };
    

    And last, although you really should not use inline event handlers, but if you have to:

    <input ... onchange="handler.call(this)" />
    

    where handler is like the handlers shown above.


    Further reading:

    • jQuery documentation
    • MDN JavaScript Guide
    • quriksmode.org Introduction to Events
    0 讨论(0)
  • 2020-12-31 03:26
    $('input:checked').click(function() {
       //do something
    });
    

    See http://api.jquery.com/checked-selector/ and http://api.jquery.com/checkbox-selector/

    0 讨论(0)
提交回复
热议问题