0

I have a select field with some options in it. Now I need to select one of those options with jQuery. But how can I do that when I only know the value of the option that must be selected?

I have the following HTML:

<div class="id_100">
  <select>
    <option value="val1">Val 1</option>
    <option value="val2">Val 2</option>
    <option value="val3">Val 3</option>
  </select>
</div>

I tried to do this with a tag but this does not work.

Please tell me about other ways.

Thanks in advance

2 Answers2

1

Not sure if you are asking about jQuery selector of select option. If that's the case, check the snippet bellow.

Example:

$('select option[value="VALUE_YOU_WANT_TO_SELECT"]')

$(document).ready(function() {
  //selects the inner html of the second option tag
  console.log($('.id_100 option[value="val2"]').html());
  //OR
  console.log($('select option[value="val2"]').html());
  //OR only
  console.log($('option[value="val2"]').html());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="id_100">
  <select>
    <option value="val1">Val 1</option>
    <option value="val2">Val 2</option>
    <option value="val3">Val 3</option>
  </select>
</div>

If you want to change the select to a specific option than you can use this:

$(document).ready(function() {
  //changes selected value to the third one using the value of the jQuery selector of the thir option
  $('select').val($('option[value="val3"]').val());
});
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="id_100">
      <select>
        <option value="val1">Val 1</option>
        <option value="val2">Val 2</option>
        <option value="val3">Val 3</option>
      </select>
    </div>
Goran Stoyanov
  • 2,311
  • 1
  • 21
  • 31
-1

I'm note sure about what i understood, but i'll try !

I think the best way to do it is by adding an id attribute to each option but with the same value that the value attribute like that: <option value="val1" id="val1">Val 1</option>

Because after this, we could store the value you already know in a variable like this:

var data = "val3"; //or whatever you had 

And in JQuery we could do this: $('#'+data).attr('selected', 'selected');

Through this, we add the selected attribute to the element we want to select and we add the value selected.

Hope this helps !