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

2

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

Grease answered 18/7, 2012 at 13:52 Comment(2)
I think this happens in Firefox too, but I'm not sure.Breakfast
Not in the latest version of FF on OSX, not tried on windows though.Grease
S
9

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)
Said answered 18/7, 2012 at 14:6 Comment(4)
Note: It's generally better to use left: -3000px instead of top:-3000px (or 9999px). When you click the label using top, the focus will be set to the radiobutton and IE8 will attempt to bring it into view - having the unfortunate side effect of scrolling to the top of the page. So provided your content fits horizontally with no horizontal scroll bar it is better to use left than topGyve
The opacity property is not supported in Internet Explorer until version IE9, therefore I had to use filter:Alpha(opacity=0). mozilla-css-opacityAppropriate
@ityler22, I think you don't have to worry about that beacuse it's handled by jquery.Said
@ocanal That's interesting, I'll have to try that out! Admittedly I used your solution from a pure CSS approach so that would explain why it could work by adding the opacity with jquery.Appropriate
C
2

try this:

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

And leave the check box "visible"

Corsair answered 18/7, 2012 at 14:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.