I have a <select> element with a recursively generated list of options, like this:


It looks great when being displayed on the page like that, but I was wondering if there is a way to change the text value that gets displayed on the main <select> element. If I select "CategoryE" for example, the displayed text looks like this:


Which is logically expected, but as you can see, the selected text retains its leading whitespace and looks messy. I'm trying to go for a trim() effect that only changes the displayed value when it's selected, but retains that whitespace in the actual <option> list so you can still see how the category relates to the others in the option tree.

This code unfortunately changes both:

$("select").on("change", function() {
    var selected = $(this).children(":selected");
    var text = $(selected).text().trim();

Is there a way to accomplish what I want without saving and restoring the leading whitespace, or do I have to resort to doing that?

0 Answers