jQuery change() event in IE not triggering properly with checkbox

I have a checkbox that I’d like to show/hide an input text element. When the checkbox is checked, the textbox disappears. When the checkbox is unchecked, the textbox reappears.

This works fine in firefox:

$(document).ready(function(){
	$("#generate_name").change(function(){
		if($(this).is(":checked")){
			$("#internal_name").attr("disabled","disabled");
			//$("#internal_name").hide();
			$("#internal_name").hide("slide", {direction: "left"}, 1250);
		}
		else{
			$("#internal_name").removeAttr("disabled");
			//$("#internal_name").show();
			$("#internal_name").show("slide", {direction: "left"}, 1250);
		}
	});
});

In IE7, After checking/unchecking the checkbox, I have to click elsewhere on the page in order for the event to fire.

If I use the click event instead, the event can fire multiple times and leave a mess behind.

Any ideas to fix this? I’m using jQuery 1.3.2 and jQuery UI 1.7.2 (the most recent versions)

Since the change event is supposed to fire after the form control loses focus, you can just force it to lose focus after a click.


$("#generate_name").click(function(){
    this.blur();
}

A drawback to doing it this way, is you lose the ability to set focus on the checkbox(click or tab to it etc…), and toggle the state by using the keyboard(space bar, enter key etc…).

Well, that didn’t work (the change event wouldn’t fire).

However, your suggestion did lead me to this:

http://stackoverflow.com/questions/168596/programmatically-triggering-events-in-javascript-for-ie-using-jquery

And I implemented it like this:

$(document).ready(function(){
	
	$("form :checkbox").click(function(){
		if($.browser.msie){
			$(this).fire("change");
		}
	});
	
});

jQuery.fn.extend({
    fire: function(evttype){
        el = this.get(0);
        if (document.createEvent) {
            var evt = document.createEvent('HTMLEvents');
            evt.initEvent(evttype, false, false);
            el.dispatchEvent(evt);
        } else if (document.createEventObject) {
            el.fireEvent('on' + evttype);
        }
        return this;
    }
});

That seemed to work for both clicks and keystrokes, and doesn’t loose focus.

hm, It worked for me in ie8. Which version did you test with? Btw, whole losing focus thing could be solved by following this.blur() with this.focus()

Keep in mind IE may not be the only browser which needs help to get your desired functionality. That’s the bad thing about sniffing for it.

IE7

This seems to work too, but if you have a focus change in the change event, it will be overwritten by what’s here:

$(document).ready(function(){
	
	$("form :checkbox").click(function(){
		if($.browser.msie){
			$(this).fire("change").blur();
			$(this).focus();
		}
	});
	
});

[edit]: a simple blur/focus didn’t work.