0

I'm trying to make custom style for checkboxes using CSS/JS

This is currently located at http://www.fb-navigatio.com/markersparebank2/.

I created the style for checkbox:

.frm_checkbox label input{
    display:none;   
}
.frm_checkbox label {
    background: url("images/check_sprite.png") no-repeat scroll 0 0;
    padding: 4px 0 8px 42px;
    position:relative;
    z-index:100;
    cursor:pointer;
}
.frm_checkbox label:hover {
    background: url("images/check_sprite.png") no-repeat scroll 0 -40px;
}
.frm_checkbox label.checked{
    background: url("images/check_sprite.png") no-repeat scroll 0 -80px;    
}

Here is the JS code:

jQuery(document).ready(function($){
    var tmp = [];
    $('input:checkbox').each(function(index){
        tmp[index] = '';
    })
    $('.frm_checkbox label').click(function(index){

        if(tmp[index] == ''){
            $(this).addClass('checked');
            $(this).find('input:checkbox').addAttr('checked');
            console.log(tmp[index]);
        }else if(tmp[index] =='1') {
            tmp[index] = '0';
            $(this).removeClass('checked');
            $(this).find('input').removeAttr('checked');
            console.log(tmp[index]);
        }
        //var $checkbox = $(this).find(':checkbox');
        //$checkbox.attr('checked', !$checkbox.is(':checked'));
        //alert();
    });
});

The problem is that the checkboxes do not work. Clicking on a checkbox does not seem to check it.

Zhihao
  • 14,758
  • 2
  • 26
  • 36
FDI
  • 771
  • 1
  • 9
  • 25

1 Answers1

0

Here are some potential issues I see off the bat:

  1. jQuery doesn't have the functions addAttr and removeAttr. You should be using prop('checked', true) and prop('checked', false), as covered in this question: Setting "checked" for a checkbox with jQuery? Documentation for jQuery can be found on its website.

  2. You are setting initial values for tmp using indices from checkboxes, but are then trying to use these indices for labels. This is a bit risky. I would recommend attaching data attributes to the elements themselves: $checkbox.data('checkedState', false)

  3. Your if-else statements check for whether the tmp value equals '' or '1'. However, you also have '0', which you set when unchecking. Since you never check for '0', that means you will never be able to check a checkbox after unchecking it. You could just have two values, instead of the third default value of ''

Let me know if those suggestions solve your problem. If not, please set up a jsFiddle so that others can try out, debug, and modify the code themselves.

Community
  • 1
  • 1
Zhihao
  • 14,758
  • 2
  • 26
  • 36