views:

266

answers:

1

I've got some strange behaviour happening I can't work out. I've written some code to add some functionality to a list containing labels and checkboxes. If the user has javascript enabled, I want the checkboxes to be hidden and for the labels to become clickable and change their appearance to indicate whether or not they have been selected. Here's the code:

$(".cal_checkbox").each(function(){
$(this).hide();
var id = $(this).attr('id');
if($(this).attr('checked'))
    {
    $('#cal_checkbox_'+id).css({"font-weight":"bold"}).css({'color':'#7C001D'}) // make bold and red if selected
    .click(function(){
        $(this).attr('checked', false)
    })
    }
else
    {
    $('#cal_checkbox_'+id).click(function(){
        $(this).attr('checked', true)
    })
    }});

This works fine if I comment out the hide() line ie if the checkboxes are visible you can still click on the labels and everything changes and works. However, if I leave the hide() in and the checkboxes become invisible, the whole thing stops working. I thought that hide() simply rendered the selected element in the same way as "display: none;". Does it remove the element completely?

A: 

In your click functions, the context of 'this' will be assigned to the "'#cal_checkbox_'+id" element (which I assume is meant to be the id of the label beside the checkbox?

hide() simply updates the display css propery to none. It does not remove the element from the DOM.

If you are using the HTML element for the checkbox labels, then this would probably explain why things are messing up when you hide the checkbox.

Can you post your HTML as well as the javascript?

Rezler