Is it possible to make a listbox that changes a text, depending on what is selected?

I want to let the player choose a class at the start of the game. To help him, I want a short text under the list, which describes the class.

Something like:

<<listbox "$class">><<option "warrior">><<option "rogue">><<option "wizard">><</listbox>>
<span id="classDesc">$classDescs["warrior"]</span>

The listbox part was easy, and I can “cheat” by having an “update” link that does the replace.
But I would like to know if I could add an event to the listbox (or something equivalent), that would fetch the description of the class whose key is the current value of “$class”, or something like that.

Thanks in advance for your answers.

Your code is pretty close there, you just need to add a “change” event handler to the listbox.

To do that you’d do something like this:

<<listbox "$class">>
	<<option "warrior">>
	<<option "rogue">>
	<<option "wizard">>
<span id="classDesc">$classDescs["warrior"]</span>
	$(document).one(":passagerender", function (event) {
		$(event.content).find("select.listbox-class").on("change", function (event) {
			setTimeout(function () {
				$("#classDesc").empty().wiki("<<= $classDescs[$class]>>").fadeIn(250);
			}, 250);

That code waits for the passage to be rendered, and when it is, it attaches a “change” event handler to the listbox. When the “change” handler is triggered, it fades out the current “classDesc” text, replaces that text with the updated text from the $classDescs array, and then fades that text in. (For details on how that works, see the HTML/JavaScript change event, the SugarCube :passagerender event and the .wiki() method, plus the jQuery .one(), .on(), .find(), .fadeOut(), .fadeIn(), and .empty() methods. Also note that the <<=>> macro is shorthand version of the <<print>> macro.)

If you don’t want the fade effect, then change the four lines within the “change” event handler to just this:

			$("#classDesc").empty().wiki("<<= $classDescs[$class]>>");

Also, since the class descriptions for each class will never change, instead of storing that class description data in a story variable, you could reduce the amount of data stored in the game history by putting that data on the SugarCube setup object. You’d need to do that either in the JavaScript section or in the StoryInit special passage. For example, in the StoryInit special passage you might do:

<<set setup.classDescs = {}>>
<<set setup.classDescs.warrior = "Fighter guy who fights!">>
<<set setup.classDescs.rogue = "Sneaky guy who sneaks!">>
<<set setup.classDescs.wizard = "Magic guy who... magics.  Er, casts magic.">>

and then you’d just change the “<<= $classDescs[$class]>>” code to “<<= setup.classDescs[$class]>>”.

Enjoy! :grinning: