Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Watch for change of the input[type="checkbox"]

Tags:

jquery

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:

(function($) {
    $.fn.checking = function() {
        if ($('.checbox').prop('checked', false) === true) {
            $('.new-checkbox').prop('id', 'unchecked');
        } else {
            $('.new-checkbox').prop('id', 'checked');
        }
    };
})(jQuery);


$(document).ready(function() {

    $('.checkbox').wrap('<div class="checkbox-wrapper"></div>');
    $('.checkbox-wrapper').append('<p class="new-checkbox">Blue = Checked, Red = Unchecked</p>');
    $('.checkbox').checking();
    $('.checbox').bind('change', function() {
        $(this).checking();

    });

});

PlayGround: LIVE DEMO

like image 223
Iladarsda Avatar asked Jul 04 '11 13:07

Iladarsda


2 Answers

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.

like image 94
Felix Kling Avatar answered Nov 16 '22 01:11

Felix Kling


Is this what you want? I am under the impression that you are over-complicating things.

$('input[type="checkbox"]').change(function() {
    alert ("The element with id " + this.id + " changed.");
});
like image 28
Jon Avatar answered Nov 16 '22 02:11

Jon