skip to Main Content

I am using material css for my web page design. I am having one single select country list dropdown and the values

<select id="select_id" name="select_id" required>
  <option value="8">select1_1</option>
  <option value="15">select2_2</option>
</select>
 $(document).ready(function() {
   $('select').formSelect();
 });

My select option are populating from a database which has an underscore in its value. I want to update the select option value at runtime on the client side and remove the underscore from options.

<select id="select_id" name="select_id" required>
  <option value="8">select1</option>
  <option value="15">select2</option>
</select>

Is there is any better way to update it using jQuery. Thanks for the help

2

Answers


  1. You should keep the original value as "value" prop of the <option> tag. For the option text the best way to handle it is to create a parser parseOptionText(optionText: string): string, in this way you have full control over the logic of the parsing and the code is easy to maintain.

    As final result you should have:

    <option value={originalValueFromDB}>parseOptionText(originalValueFromDB)</option>
    

    And

    const parseOptionText = (optionText: string): string => {
        return optionText.replace('_', '');
    }
    
    Login or Signup to reply.
  2. While changing at the source is the better solution, you can update the text of an option using the .text() overload that accepts a function:

    $("select option").text((i, txt) => txt.replace(/_.*$/, ''))
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <select id="select_id" name="select_id" required>
      <option value="8">select1_1</option>
      <option value="15">select2_2</option>
    </select>

    remove the underscore from options

    the above matches your sample that removes both the underscore and what follows it, to remove just the underscore:

    $("select option").text((i, txt) => txt.replace(/_/g, ''))
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search