Jquery show () / hide () problem in Internet Explorer?

The following HTML works in Firefox, but for some reason does not work in IE (Label2 not shown). Is this a mistake or am I missing something?

Any help would be appreciated.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <script src="http://jqueryjs.googlecode.com/files/jquery-1.2.6.min.js" type="text/javascript"> </script> <script> jQuery(document).ready(function(){ function setVis(){ var val = $("#check").is(":checked"); if (val) $("#g_1").show(); else $("#g_1").hide(); } setVis(); $("#check").change(setVis); }); </script> </head> <body> <span> <input type="checkbox" id="check" /> <label>Label1</label> </span> <span id="g_1"> <label>Label2</label> </span> </body> </html> 
+8
jquery internet-explorer
Dec 15 '08 at 15:57
source share
3 answers

Cause:

In MSDN change the event is

... is triggered when the content is committed and not while changing the value. For example, in a text field, this event is not fired during user input, but when the user commits, change, leaving the text field that has focus.

The behavior for the flags is similar: in IE, the event does not fire until the focus is removed from the element (try it: click, then clear the check box and the behavior will be as expected). Firefox does not seem to honor this difference.

Decision:

Use click event handler instead of change :

  $("#check").click(setVis); 

... and the behavior should be consistent between browsers.

+15
Dec 15 '08 at 16:22
source share

Remember that the onchange event is fired after you check the box, and then leave the box checked . Did you try to check it and then click elsewhere in the document?

You might want to use click and keystroke in jQuery instead (to check a field with a click and space).

<sidequestion> Is there a reason why you declare / define a function in your finished paragraph of the document, and not outside it? </sidequestion>

Another edit; can i recommend this more elegant code:

 jQuery(document).ready(function(){ $("#g_1").hide(); $("#check").change(function() { $("#g_1").toggle(); }); }); 
+5
Dec 15 '08 at 16:09
source share

Change the .change event to .click. the result is the same in both browsers. in IE, when you click this check box, no blurring occurs.

+1
Dec 15 '08 at 16:29
source share



All Articles