user2696536
user2696536

Reputation: 63

Detecting a property checked on a check box and applying a class

I have been using the following code to update div styles when a check box is checked:

http://jsfiddle.net/tPawr/6/

$(document).ready(function() {
    var checkbox = $('input[type="checkbox"]');
    var checkimage = $('<div class="checkbox-image" />');
    $(checkbox).each( function() {
        $(this).show().before( checkimage );
    });
    $(checkbox).prop('checked', function() {
        $('.checkbox-image').addClass('checked');
    });
    $('checkbox-image').on('click',function() {
        $(this).toggleClass('checked').after().prop('checked',$(this).is('.checked'));
    });
});

It was working fine, and then it stopped working and I can't work out why? Can anyone help?

Upvotes: 0

Views: 62

Answers (2)

Barmar
Barmar

Reputation: 780724

You left out a dot:

$('.checkbox-image').on('click',function(){
   ^

FIDDLE

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388316

jQuery library was not included in the fiddle - (In the LHS panel, first dropdown select the jQuery version)

Your checkbox-image selector was wrong as it missing the . in front.

Also the code could be simplified as

$(document).ready(function() {

    var checkbox = $('input[type="checkbox"]');
    var checkimage = $('.checkbox-image');

    checkimage.click(function(){
        $(this).toggleClass('checked').next().prop('checked',$(this).is('.checked'));
    }); 

    checkbox.change(function(){
        checkimage.toggleClass('checked', this.checked)
    }).change();

});

Demo: Fiddle

Upvotes: 0

Related Questions