0

Suppose I have a select tag as following:

<select name='selectBox' id='selectBox'>
    <option value='1'>one</option>
    <option value='2'>two</option>
    <option value='3'>three</option>
    <option value='4'>four</option>
    <option value='5'>five</option>
</select>

and I have a value in a variable, for example: selectVal = 'three' and I want to select the option based on text not on value.

I looked on

$('#selectBox').prop('selectedIndex', 3);
$('#selectBox').selectmenu('refresh');

But I want to select on text of option. I'm beginner in this stuff, any help will be highly appreciated!

Thanks.

Asad ullah
  • 620
  • 2
  • 9
  • 26
  • 1
    Possible duplicate of [How to select an option by its text?](https://stackoverflow.com/questions/3744289/how-to-select-an-option-by-its-text) – Dexygen Aug 12 '18 at 11:30
  • Possible duplicate of [How to populate the options of a select element in javascript](https://stackoverflow.com/questions/6601028/how-to-populate-the-options-of-a-select-element-in-javascript) – Feras Al Sous Aug 12 '18 at 11:31

4 Answers4

1

You have to get the options index:

 var options = $("#selectBox > option");
 $('#selectBox').prop('selectedIndex', options.index(":contains(three)"));
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
1

try this:-

var text = "five"
$(document).ready(function() {
  $('#selectBox option').each(function(index){
    if($(this).text() === text){
        $('#selectBox').prop('selectedIndex', index);
    }
  })
});
Atul
  • 420
  • 2
  • 10
1

You can try the following way by using each():

let selectVal = 'three';
$('#selectBox option').each(function(){ 
  if($(this).text() == selectVal)
    $('#selectBox').prop('selectedIndex', 2);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name='selectBox' id='selectBox'>
    <option value='1'>one</option>
    <option value='2'>two</option>
    <option value='3'>three</option>
    <option value='4'>four</option>
    <option value='5'>five</option>
</select>
Mamun
  • 66,969
  • 9
  • 47
  • 59
0

This is pure vanilla js

var element = document.getElementById(id);
element.value = valueToSelect;