Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clicking on label not checking checkbox if hidden when using IE 7 or 8

I am trying to create a custom designed checkbox using the label associated to a checkbox element and hiding (display:none) the checkbox.

This works fine in all browsers except IE, which requires the checkbox to be visible for the label to be clickable.

Here's my code...

HTML

<input type="checkbox" id="myCheck" />​

CSS

label.checkbox {
    border:1px solid #666;
    width:25px;
    height:23px;
    display:block; 
}​

jquery

$("input[type=checkbox]").each(function() {
    $(this).hide().before('<label for="' + $(this).attr("id") + '" class="checkbox"></label>');
});

$("input[type=checkbox]").live('change', function() {
    if ($(this).prop('checked') == true) {
        $('label[for=' + $(this).attr("id") + ']').html("X")
    } else {
        $('label[for=' + $(this).attr("id") + ']').html("")
    }
});​

Or jsfiddle

like image 975
Tom Avatar asked Jul 18 '12 13:07

Tom


People also ask

Should checkbox label be clickable?

This allows users to activate the element by clicking the label. It doesn't take much to improve the user experience when all you have to do is add a short line of code. Making your checkbox labels clickable can not only do wonders for motor-impaired users but every user on your site.

What is checkbox hack?

The Checkbox hackClicking on the label will check a hidden checkbox. Once checked, the elements with the .to-be-changed class will become red. Re-clicking the label will uncheck the checkbox, restoring the default color of the .to-be-changed elements. Demo.


2 Answers

I don't know whether there is a more efective way to do this, but you can do this by setting checkbox element position out of the page,

.hiddenEl {
   position:absolute;
   top: -3000px;
}


$("input[type=checkbox]").each(function() {
    $(this).addClass("hiddenEl").before('<label for="' + $(this).attr("id") + '" class="checkbox"></label>');
});

DEMO


UPDATE

And also you can set checbox opacity to zero, that will hide it without "dispayl:none",

$(this).css("opacity", 0)

or

$(this).fadeTo(0, 0)
like image 112
Okan Kocyigit Avatar answered Sep 28 '22 08:09

Okan Kocyigit


try this:

#myCheck{
  position:absolute;
  left:-9999px;
  }

And leave the check box "visible"

like image 24
Carsen Avatar answered Sep 28 '22 08:09

Carsen