How to listen to when a checkbox is checked in Jquery

前端 未结 7 1855
栀梦
栀梦 2020-12-08 12:47

I need to know when any checkbox on the page is checked:

e.g.


I tried this in Jquery



        
相关标签:
7条回答
  • 2020-12-08 13:13
    $("input[type='checkbox']").click(function(){
        alert("checked"); 
    });
    

    Just a normal .click will do.

    0 讨论(0)
  • 2020-12-08 13:15
    $("input:checkbox").change(function(){
    
    alert($(this).val());
    
    });
    

    here is the fiddle http://jsfiddle.net/SXph5/

    jquery change

    0 讨论(0)
  • 2020-12-08 13:21
    $('input:checkbox').live('change', function(){
        if($(this).is(':checked')){
            alert('checked');
        } else {
            alert('un-checked');
        }
    });
    

    jsfiddle: http://jsfiddle.net/7Zg3x/1/

    0 讨论(0)
  • 2020-12-08 13:22

    If you want to use .on this works

     jQuery('input[type=checkbox]').on('change', function() {
       if (this.checked) {
         console.log('checked');
       }
     });
    
    0 讨论(0)
  • 2020-12-08 13:33
    $('input:checkbox').change(function(){
        if($(this).is(':checked')){
            alert('Checked');
        }
    });
    

    Here is a demo

    0 讨论(0)
  • 2020-12-08 13:36

    Use the change() event, and the is() test:

    $('input:checkbox').change(
        function(){
            if ($(this).is(':checked')) {
                alert('checked');
            }
        });
    

    I've updated the above, to the following, because of my silly reliance on jQuery (in the if) when the DOM properties would be equally appropriate, and also cheaper to use. Also the selector has been changed, in order to allow it to be passed, in those browsers that support it, to the DOM's document.querySelectorAll() method:

    $('input[type=checkbox]').change(
        function(){
            if (this.checked) {
                alert('checked');
            }
        });
    

    For the sake of completion, the same thing is also easily possible in plain JavaScript:

    var checkboxes = document.querySelectorAll('input[type=checkbox]'),
        checkboxArray = Array.from( checkboxes );
    
    function confirmCheck() {
      if (this.checked) {
        alert('checked');
      }
    }
    
    checkboxArray.forEach(function(checkbox) {
      checkbox.addEventListener('change', confirmCheck);
    });
    

    References:

    • JavaScript:
      • Array.from().
      • Array.prototype.forEach().
      • document.querySelectorAll().
      • EventTarget.addEventListener().
    • jQuery:
      • :checked.
      • change().
      • is().
    0 讨论(0)
提交回复
热议问题