Unable to shorten the visible content in the dropdown

When a user selects text from the dropdown menu, I want to remove any extra spaces. However, I am having trouble implementing this feature.

/*  $("#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>

The displayed value in the selection should show the trimmed text.

Note:- The value selected in the dropdown should only display the trimmed text when shown, while the options should remain as they are.

https://i.sstatic.net/lQXqO749.png

Answer №1

Check out this updated version utilizing data attributes for value storage

$(() => {
  const handleOptionValues = (selectElement, save=false) => {
    $(selectElement).find('option').each(function() {
      if (save) this.dataset.value = this.value; // Save initial value to data-value
      else this.value = this.dataset.value; // Reset value from data-value
    });
  };
  $('#input_14').on('change', function() {
    handleOptionValues(this); // reset
    // Retrieve the selected option
    var selectedOption = $(this).find('option:selected');
    // Trim spaces and set it back as the value
    var trimmedValue = $.trim(selectedOption.val());
    selectedOption.val(trimmedValue);
  });
  handleOptionValues('#input_14', true); // initialize
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<select id="input_14">
  <option value="number:1906">&nbsp;&nbsp;&nbsp;&nbsp;sw</option>
  <option value="number:1907">&nbsp;&nbsp;&nbsp;&nbsp;s</option>
  <option value="number:1910">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;dsdsdsds</option>
  <option value="number:1909">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;swww</option>
</select>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Check if the URL is correct (server response = 200)

Is it possible to validate the URL provided by a user in a form by checking if the server's response is 200? I aim to perform this validation when the user enters information in the field and when it loses focus. Due to the same origin policy, I exec ...

Combining rows and columns in Flexbox design

https://i.stack.imgur.com/tDLii.png I'm able to easily create this layout using the float property, but I'm having some difficulties achieving the same with flexbox. CSS: .a { background: red; float: left; width: 30%; ...

Javascript's regular expression can be utilized to detect an img tag that has no specified image source (src="")

My specific need is to eliminate all img tags that do not have the attribute "img" specified within them. I attempted to accomplish this using a regular expression - content.replace(/<img[^>]*>/g,""). However, this approach removes all img tags ...

Testing React components using the React Testing Library

I've been working on creating a test unit for my React Application using React Testing Library, but I've hit a roadblock. I've gone through all the documentation but I'm still stuck. The API was set up using create React app. One of th ...

Activate jQuery function upon clicking a bootstrap tab

When I click on a Bootstrap tab, I want to trigger an AJAX function. Here is the HTML code: <li><a href="#upotrebljeni" data-toggle="tab">Upotrebljeni resursi</a></li> The jQuery AJAX function looks like this: $('a #upotreb ...

What criteria does jQuery's .ajax function use to identify a request as 'failed'?

Interestingly, it seems that the documentation for .ajax does not explicitly define the terms 'success' and 'fail'. While there are some basic guidelines like: Any status code in the 4xx or 5xx range triggers a .fail() callback Any s ...

"Customize your text alignment with TinyMCE's align

I'm in the process of updating from an outdated version of TinyMCE to the most recent release. In the old TinyMCE, if you inserted an image and aligned it to the left, the HTML generated looked like this: < img src="testing.jpg" align="left" > ...

Searching for all classes and IDs in a CSS Stylesheet that include a specific keyword

I am currently working with a premium WordPress theme that has an extensive styles.css file consisting of over 25,000 lines. My goal is to make sitewide changes to the font and main color, and in order to do this effectively, I need to identify all classes ...

(Discord.JS) Bot failing to send direct message upon user joining the server

When attempting to send a DM message, I am using the following code: bot.on('guildMemberAdd', (member) => { member.send('a'); }); I am experiencing difficulty in understanding why the private message is not being successfully se ...

Guide to creating a TypeScript library for the browser without relying on any NodeJS API or modules

After working on some code that utilizes plain browser Javascript APIs and can be executed within a browser HTML environment (served by IIS Server or Chrome Extensions), I am eager to contribute to the community by creating a library that is not currently ...

Retrieve information from a JSON script using C#

I need to extract data from a homepage, but the information I'm looking for is embedded in a JSON script. How can I retrieve this value? For example: <div id="contentWrap"> <div id="contentTextWrap"> <div id="contentText ...

What is the best way to trigger a method in Angular when a user leaves an input field blank?

I have implemented controller methods to trigger upon changes in this specific input field: <input type="text" ng-model="query" ng-model-options='{ debounce: 500 }' ng-change="searchOnTags(query)"/> Is there a way to call a separate metho ...

Why is it not possible for me to choose an element after it has been placed within a grid component?

Struggling to eliminate the blur effect on an image inside a grid element? It seems modifying the properties of an element within a grid class is causing some issues. To simplify, I conducted a basic test: I managed to change the ppp2 class when hovering ...

Fetching POST variables in ASP.NET with ajax: A step-by-step guide

When it comes to sending an AJAX request, I use the following code snippet: $.ajax({ url: "/Home/ShowStadium", contentType: "application/json; charset=utf-8", dataType: "text", type: "POST", data: Club, success: function (data) { $(".r ...

What could be causing my HTML form to only accept one response at a time?

While conducting my study, I required a Likert scale and came across a well-designed one at https://codepen.io/Buttonpresser/pen/poXVod However, I encountered an issue where selecting an answer for one question would deselect the answer for a different qu ...

The Jquery click function seems to be malfunctioning when triggered using a laptop mouse tracking pad, but functions properly otherwise

I am facing an issue on my webpage where I use a typing input to search for certain IDs using the typeahead library from jQuery. Oddly, when I click on the search results that are displayed in a list by an external mouse, everything works perfectly fine. H ...

Having trouble with mapping a localStorage variable containing an Array of Objects, which results in the item disappearing

In my localStorage, I have an array called product_categories that contains various objects, each consisting of a string and a nested array of objects representing products belonging to each category. Despite seeking help from Appery's support team o ...

Encountering a problem with the persistent JavaScript script

I have implemented a plugin/code from on my website: Upon visiting my website and scrolling down, you will notice that the right hand sidebar also scrolls seamlessly. However, when at the top of the screen, clicking on any links becomes impossible unless ...

Having trouble aligning the canvas of threejs next to a div

I am currently working on a shoe customizer project and facing difficulties in aligning my canvas (using three.js) next to the shoe customizer div. Although I posted the same question earlier, I did not receive a satisfying solution. I made some adjustment ...

Generating JSON responses using Django REST framework to facilitate table visualizations on the front end

I am facing an issue with my django-rest-framework where I am trying to display a table using the Google Chart data drawing library. However, I keep encountering an error message saying "You called the draw() method with a String rather than a DataTable or ...