Watch for change of the input[type=“checkbox”]

前端 未结 5 1970
旧时难觅i
旧时难觅i 2021-02-13 15:17

How can I run a function on checkbox change?

I\'m trying to write small checkbox replacing function base on that - but I\'m doing something wrong.

Code:

5条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-13 15:47

    $('.checkbox').change(function(){
        alert('changed');
    })
    

    I usedthe class you placed on the checkbox (.checkbox) for this. It detects a change in the state of the checkbox (this works for other inputs as well)

    The example I included alerts 'changed' one the checkbox is clicked or unclicked.

    If you want to know if it is checked or not every time then:

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

提交回复
热议问题