Hello again. finally remembered to fix this.
Yeah, I know it would be easier to use the focus() event. But, IMHO, the beauty of jQuery is to be able to shorten JavaScript code as much as possible. As they're infamous mantra goes, "write less, do more".
Anyways, on second look of my code. The problem was obviously that my code was not remembering the last category when switching between the two. Thus, creating a bug. So, I made the appropriate fixes.
Code:
$("select").change(function () {
var oldc;
return function (event) {
var foo = $("select option:selected"),
bar = foo.text(),
cat = foo.parent().attr("label");
if (oldc) { // This won't exist the first time we run this
oldfoo = $("select option:contains('" + oldc + ":')");
oldHTML = oldfoo.html();
oldHTML && oldfoo.html(oldHTML.replace(oldc + ': ', ''));
}
foo.text(cat + ': ' + bar);
oldc = cat; // Remember it for next time
};
}());
JSFiddle Linkage
By this time, I was having so much fun, I was just staring blankly at the screen when; BAM!
Epiphany.
The profound solution was not to search for or save the last category but to use other special characters found on the list. That's right the colon.
The result, a beautiful jQuery four-liner.
Code:
$("select").change(function (event) {
var foo = $("select option:selected"),
bar = foo.text(),
cat = foo.parent().attr("label"),
old = $("select option:contains(':')"),
oldb = old.html();
oldb && old.html(oldb.replace(oldb.substr(0, oldb.indexOf(':') + 2),''));
foo.text(cat + ': ' + bar);
});
JSFiddle Linkage
Note: I say four-liner because this script is basically just four lines of code. Just edited for readability.
Thank you TS for taking away the boring times.