-1

I have the following select element:

<select name="sub-concUnit" class="select form-control" required id="id_sub-concUnit">
  <option value="" selected></option>
  <option value="22">mg/ml</option>
  <option value="23">µg/ml</option>
  <option value="24">mM</option>
  <option value="25">µM</option>
</select>

I need to get the value of the option with the text 'mg/ml'. Note that 'mg/ml' is not the selected option.

The idea is to be able to do something like this:

var sel = Get option value for which text is mg/ml;
$("#id_sub-concUnit").val(sel);

Right now, I have to hard code the value of the option with text mg/ml.

I have tried:

var sel = $("id_sub-concUnit").find('option[text="mg/ml"]');

as suggested here, but this returns an empty object.

kbr85
  • 1,416
  • 12
  • 27
  • Have you also read the other mentioned post? – Reporter Apr 06 '23 at 10:30
  • May be https://www.educba.com/jquery-select-option/ does also your answer. – Reporter Apr 06 '23 at 10:32
  • @Reporter, the other answer mentioned in the post and the link are not related to what I need. I need to find a way to get the value 22 by searching for the text 'mg/ml' inside the select element. – kbr85 Apr 13 '23 at 12:19
  • You should try following the advice given in the **answers** to [this duplicate](https://stackoverflow.com/questions/11950434/find-select-option-by-text) instead of trying to implement the broken attempt that the question is asking about. – Quentin Apr 15 '23 at 23:06

1 Answers1

0

I tried this question either and got also a null value back. With support of https://www.educba.com/jquery-select-option/ - which was mentioned in the comments- I could create a working example:

    $(document).ready(function() { 
      $("#id_sub-concUnit").val(getValueByText("id_sub-concUnit","µg/ml")); 
    });
    
    function getValueByText(objectId, textValue)
    {
      returnValue = "";
      $("#"+ objectId).find('option').each(function()
      {
        if ($(this).text().indexOf(textValue) > -1)
        {
          returnValue = $(this).val();
        }
      });
      return returnValue;
    }

Hope I did understand you right and this is what you looking for.

Reporter
  • 3,897
  • 5
  • 33
  • 47