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

前端 未结 5 1985
旧时难觅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:37

    You have some typos and errors in your script.

    if($('.checbox').prop('checked', false) === true)
    //         ^                   ^^^^^^^^^^^^^^^^^
    

    should be

    if(this.prop('checked'))
    

    if($('.checkbox').prop('checked')) would work too of course, but why select the element again, if you already made it a plugin and the element is available via this?

    And

    $('.checbox').bind('change', function(){
    //      ^
    

    should be

    $('.checkbox').bind('change', function(){
    //      ^
    

    Working demo: http://jsfiddle.net/fkling/yGBAK/40/

    That said, it is better (more logical) to add and remove a class than changing the ID of the element.

提交回复
热议问题