Strange jQuery Behavior

April 28, 2009

Development

I’ve discovered some strange behavior with at work today. I have an element that when changed is checked for a condition. If the condition is met, I disable a form element on the screen, and then if the condition ever becomes false, I allow this element again. (In addition to merely disabling the element, I style it a bit differently for the sake of my end users.) So in summary, I’m adding/removing the disabled attribute and a class on form element based upon a user interaction.

This is very easy chaining jQuery, but I have noticed something odd about the order of the chained commands. The code snippet:


if(condition) {

	$("#my_element_id")
		.attr("disabled","disabled")
		.addClass("disabled");

	} else {

	$("#my_element_id")
		.removeClass("disabled")
		.attr("disabled","");

}

Notice that in each block of the if statement the order in which I call the chain is different. If the condition is true, I add the attribute and then the class, where as if it is false I remove the class and then the attribute. No big deal right?

Well, this is the weird part: if the element’s modification doesn’t maintain this exact order, for whatever reason, jQuery completely ignores the addClass function. The attributes are modified as desired, but it just won’t add the class for me. I can’t figure it out.

,

No comments yet.

Leave a Reply