html – Dynamically changing selected via jQuery

Question:

There is such a hierarchical DropDown.

<select id="estimateA">
    <option value="1">Test</option>
    <option value="2">\u00a0_Test1</option>
    <option value="3">\u00a0\u00a0_Test1_1</option>
    <option value="4">\u00a0_Test2</option>
    <option value="5">\u00a0\u00a0_Test2_1</option>
    <option value="6">\u00a0\u00a0_Test2_2</option>
</select>

Tell me how to make sure that there are no extra spaces on the selected element?

Now I do it as follows:

 $('#estimateA').change(function () { 
    //возвращаю элементам неразрывные пробелы
    $("#estimateA option").each( 
    function paintPackageTable() {
        var $cell = $(this);
        $cell.text($cell.text().replace(/  /g, '\u00a0\u00a0'));
        }
    );
    //возвращаю элементам неразрывные пробелы
    var $cell1 = $("#estimateA option:selected");
    $cell.text($cell1.text().replace(/\u00a0\u00a0/g, '  '));
}); 

those. so that the hierarchy is visible in the drop-down list, and when selected and displayed in a "collapsed" state, there are no extra spaces?

Update

When "expanding" the dropdown, where non-breaking spaces are replaced with regular text, the text is "pressed" to the left margin. And I want it to cuddle only when the list is collapsed and the "hierarchy" in it is not violated

Answer:

As a temporary solution did so, the problem remained – when "expanding" the selected item breaks the hierarchy.

$(function() {
  $("#estimateA").on("change", function(event) {
    $("#estimateA option").each(function() {
      var $cell = $(this);
      $cell.text($cell.text().replace(/\u200B/g, "\u2007"))
    });
    var $cell = $("#estimateA option:selected");
    $cell.text($cell.text().replace(/\u2007/g, "\u200b"))
  })
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id="estimateA">
  <option value="1">Test</option>
  <option value="2">&#8199;_Test1</option>
  <option value="3">&#8199;&#8199;_Test1_1</option>
  <option value="4">&#8199;_Test2</option>
  <option value="5">&#8199;&#8199;_Test2_1</option>
  <option value="6">&#8199;&#8199;_Test2_2</option>
</select>
Scroll to Top