javascripthtmljquerycss

Not able to trim displayed value in Dropdown


I want to remove space only when user selects text from dropdown,I am not able to do that. in option it should display as it is.

/*  $("#input_13").find("option").each(function (index, option) {
        $(option).html($(option).html().replace(/ /g,''));
 }); */
$('#input_13').change(function() {
  // Get the selected option
  var selectedOption = $(this).find('option:selected');
  // Get the current text, trim spaces, and set it back
  var trimmedText = $.trim(selectedOption.text());
  selectedOption.text(trimmedText);
  // Optionally, update the value attribute if needed
  // $(this).val(trimmedText);
  console.log($("#input_13 option:selected").text())
});
<select id="input_13">
  <option label="&nbsp;&nbsp;&nbsp;&nbsp;sw" value="number:1902">&nbsp;&nbsp;&nbsp;&nbsp;sw</option>
  <option label="&nbsp;&nbsp;&nbsp;&nbsp;s" value="number:1903">&nbsp;&nbsp;&nbsp;&nbsp;s</option>
  <option label="&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;dsdsdsds" value="number:1906">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;dsdsdsds</option>
  <option label="&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;swww" value="number:1905">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;swww</option>
</select>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

Here it should display trimmed value in selection.

Note:- Drop-down Selected value should be display only when displayed and in option it should display as it is.

enter image description here


Solution

  • Here is a version that uses data attributes to store the values

    $(() => {
      const handleOptionLabels = (selectElement, save=false) => {
        $(selectElement).find('option').each(function() {
          if (save) this.dataset.label = this.textContent; // Save initial text to data-label
          else this.textContent = this.dataset.label; // Reset text from data-label
        });
      };
      $('#input_13').on('change', function() {
        handleOptionLabels(this); // reset
        // Get the selected option
        var selectedOption = $(this).find('option:selected');
        // Get the current text, trim spaces, and set it back as the label
        var trimmedText = $.trim(selectedOption.text());
        selectedOption.text(trimmedText);
      });
      handleOptionLabels('#input_13', true); // initialise
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <select id="input_13">
      <option value="number:1902">&nbsp;&nbsp;&nbsp;&nbsp;sw</option>
      <option value="number:1903">&nbsp;&nbsp;&nbsp;&nbsp;s</option>
      <option value="number:1906">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;dsdsdsds</option>
      <option value="number:1905">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;swww</option>
    </select>