Kevin
Kevin

Reputation: 309

How to Hide the Certain Text Value of Selected Option using jQuery

I have a select box that contains certain elements (see below):

    <select id="test" name="test">
         <option value="12345">12345 - Test</option>
         <option value="67890">67890 - Test 2</option>
         <option value="53453">53453 - Test 3</option>
    </select>

Here is what I'm trying to accomplish When the user selects a certain element, I want certain elements of the text to hide. For example, if I select 12345, I want the - Test to hide.

How can I do it in jQuery?

Thank you, Kevin

Upvotes: 0

Views: 573

Answers (2)

Kevin
Kevin

Reputation: 309

I have found a solution:

Here is how I achieved it:

        $('select[name="test"]').find('option').remove().end();
        $('select[name="test"]').append(new Option(selectId, selectId));
        $('select[name="test"]').trigger('change');

Upvotes: -1

Tyler Stoney
Tyler Stoney

Reputation: 428

A brute force-y way to do it would be to keep track of the internal text and values of the currently-selected option, then replace the text with the desired text when the option changes. This part's easy in your case, since the desired output text is the same as the option's value.

I opted to add a blank option at the beginning, since by default the text will not have changed, but you can get around this by adding a trigger to go off when the page is finished loading.

var selectedTextOrig = "";
var selectedValue = 0;
$("#test").change(function() {
  // Reset the inner html text for the previously-selected option
  $("#test option").each(function() {
    if ($(this).val() == selectedValue) {
      $(this).text(selectedTextOrig);
      return false; // break out of $.each()
    }
  });

  // Store the viewable text and value of the currently selected 
  selectedValue = $("#test option:selected").val();
  selectedTextOrig = $("#test option:selected").text();

  // Replace the current inner html
  $("#test option:selected").text(selectedValue);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<select id="test" name="test">
  <option disabled="disabled" selected></option>
  <option value="12345">12345 - Test</option>
  <option value="67890">67890 - Test 2</option>
  <option value="53453">53453 - Test 3</option>
</select>

Upvotes: 2

Related Questions