AddClass and removeClass do not work in Internet Explorer

The jQuery addClass and removeClass functions do not work properly when I use them to change the appearance of a checkbox in Internet Exploer (IE). However, they work fine in other browsers.

Here is a sample code illustrating my problem:

$('input:#chkbox').click(function() { //if($(this).is(":checked")){ if($('input:#chkbox').is(":checked")) { $('input:#chkbox').next("label").addClass("etykieta_wybrana"); } else { $('input:#chkbox').next("label").removeClass("etykieta_wybrana"); } }); 

To further verify this, you can run the code using jsFiddler (does not work in IE): http://jsfiddle.net/tejek/pZJMd/

+7
source share
2 answers

Your selector must be $('#chkbox') if you want it to work with only one flag, with the identifier chkbox, or it should be $('input:checkbox') if you want it to work with each a flag.

In addition, it is better to use the change event instead of the click event, because the click event (theoretically) should not fire if the change was made by anything other than a mouse click.

Maybe try something like this:

 $('input:checkbox').change(function () { var $this = $(this); if( $this.is(':checked') ) { $this.next('label').addClass('etykieta_wybrana'); } else { $this.next('label').removeClass('etykieta_wybrana'); } }); 

See DEMO .

If this does not help, try adding and removing classes manually in HTML to see maybe the problem is not adding classes, but not showing the effects of adding classes with some strange quirks mode mode or something kind.

Be sure to run your HTML code something like this:

 <!doctype html> <html lang="en-us"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=Edge;chrome=1"> 

to ensure you always get the most out of your IE rendering engine.

+4
source

This input:#chkbox seems weird. Try #chkbox if you only have one element with the identifier #chkbox (and this will be the <input /> field).

In addition, you should probably cache the result of $('#chkbox') , for example:

 var $chkbox = $('#chkbox'); $chkbox.click(function() { if ($chkbox.is(":checked")) { $chkbox.next("label").addClass("etykieta_wybrana"); } else { $chkbox.next("label").removeClass("etykieta_wybrana"); } }); 

You can even use .toggleClass() with switch (second argument, unchecked):

 var $chkbox = $('#chkbox'); $chkbox.click(function() { $chkbox.next("label").toggleClass("etykieta_wybrana", $chkbox.is(":checked")); }); 

Renouncement
No, this does not explain why it worked in Fx, Chrome, etc., and not in IE. I assume that the implementation of the selector is slightly different between browsers. In general, this may not even solve the problem, but only hint at potential problems (and a β€œcleaner” solution).

+1
source

All Articles