47

How to set selectedIndex of select element using display text as reference?

Example:

<input id="AnimalToFind" type="text" />
<select id="Animals">
    <option value="0">Chicken</option>
    <option value="1">Crocodile</option>
    <option value="2">Monkey</option>
</select>
<input type="button" onclick="SelectAnimal()" />

<script type="text/javascript">
    function SelectAnimal()
    {
        //Set selected option of Animals based on AnimalToFind value...
    }
 </script>

Is there any other way to do this without a loop? You know, I'm thinking of a built-in JavaScript code or something. Also, I don't use jQuery...

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
kazinix
  • 28,987
  • 33
  • 107
  • 157
  • The loop is working, but I wonder is there any way I can do it without a loop? And also, no jQuery? – kazinix Jun 02 '11 at 04:44

7 Answers7

64

Try this:

function SelectAnimal() {
    var sel = document.getElementById('Animals');
    var val = document.getElementById('AnimalToFind').value;
    for(var i = 0, j = sel.options.length; i < j; ++i) {
        if(sel.options[i].innerHTML === val) {
           sel.selectedIndex = i;
           break;
        }
    }
}
Jacob Relkin
  • 161,348
  • 33
  • 346
  • 320
  • No loop, no jQuery, is it possible? – kazinix Jun 02 '11 at 04:43
  • Why do you use that `j` there? – Juan Jul 09 '14 at 08:58
  • 1
    @JuanLuisSoldi So I don't recalculate `sel.options.length` more times than I absolutely have to. – Jacob Relkin Jul 09 '14 at 20:13
  • 2
    @JacobRelkin I know this is an old post, but I felt that I needed to point out that `sel.options.length` does not calculate anything as it it is not a function. You are accessing a variable contained in the `sel.options` object. The `j = sel.options.length` is not necessary. – Sintrias Oct 16 '19 at 19:21
9
<script type="text/javascript">
     function SelectAnimal(){
         //Set selected option of Animals based on AnimalToFind value...
         var animalTofind = document.getElementById('AnimalToFind');
         var selection = document.getElementById('Animals');

        // select element
        for(var i=0;i<selection.options.length;i++){
            if (selection.options[i].innerHTML == animalTofind.value) {
                selection.selectedIndex = i;
                break;
            }
        }
     }
</script>

setting the selectedIndex property of the select tag will choose the correct item. it is a good idea of instead of comparing the two values (options innerHTML && animal value) you can use the indexOf() method or regular expression to select the correct option despite casing or presense of spaces

selection.options[i].innerHTML.indexOf(animalTofind.value) != -1;

or using .match(/regular expression/)

Ibu
  • 42,752
  • 13
  • 76
  • 103
  • Hm, is there any other way to do this without a loop? You know, I'm thinking of a built-in JavaScript code or something. Also, I don't use jQuery... – kazinix Jun 02 '11 at 04:42
  • actually this loop is effective because as soon as the condition is met, the loop stops. thats why i use the `break;` command – Ibu Jun 02 '11 at 04:47
  • A while ago, I can't (not enough reputation). But now you commented, I gained reputation or privileges rather, I voted your answer up. – kazinix Jun 02 '11 at 05:15
  • selection.value = animalTofind.value; // is what I have used in TypeScript projects and it seem to work fine in regard to finding the correct index – aalesund Jan 31 '22 at 16:23
5

If you want this without loops or jquery you could use the following This is straight up JavaScript. This works for current web browsers. Given the age of the question I am not sure if this would have worked back in 2011. Please note that using css style selectors is extremely powerful and can help shorten a lot of code.

// Please note that querySelectorAll will return a match for 
// for the term...if there is more than one then you will 
// have to loop through the returned object
var selectAnimal = function() {
  var animals = document.getElementById('animal');
  if (animals) {
    var x = animals.querySelectorAll('option[value="frog"]');
    if (x.length === 1) {
      console.log(x[0].index);
      animals.selectedIndex = x[0].index;
    }
  }
}
<html>

<head>
  <title>Test without loop or jquery</title>
</head>

<body>
  <label>Animal to select
  <select id='animal'>
    <option value='nothing'></option>
    <option value='dog'>dog</option>
    <option value='cat'>cat</option>
    <option value='mouse'>mouse</option>
    <option value='rat'>rat</option>
    <option value='frog'>frog</option>
    <option value='horse'>horse</option>
  </select>
  </label>
  <button onclick="selectAnimal()">Click to select animal</button>

</body>

</html>

document.getElementById('Animal').querySelectorAll('option[value="searchterm"]'); in the index object you can now do the following: x[0].index

Brandon
  • 1,036
  • 2
  • 17
  • 19
  • Could just use CSS selector `select#animals > option[value="frog"]` and save yourself a few lines. – miken32 Dec 06 '19 at 21:03
3

Try this:

function SelectAnimal()
{
    var animals = document.getElementById('Animals');
    var animalsToFind = document.getElementById('AnimalToFind');
    // get the options length
    var len = animals.options.length;
    for(i = 0; i < len; i++)
    {
      // check the current option's text if it's the same with the input box
      if (animals.options[i].innerHTML == animalsToFind.value)
      {
         animals.selectedIndex = i;
         break;
      }     
    }
}
tradyblix
  • 7,439
  • 3
  • 25
  • 29
2

You can set the index by this code :

sel.selectedIndex = 0;

but remember a caution in this practice, You would not be able to call the server side onclick method if you select the previous value selected in the drop down..

Sirko
  • 72,589
  • 19
  • 149
  • 183
ssingh
  • 563
  • 5
  • 14
0

Add name attribute to your option:

<option value="0" name="Chicken">Chicken</option>

With that you can use the HTMLOptionsCollection.namedItem("Chicken").value to set the value of your select element.

Damian
  • 2,752
  • 1
  • 29
  • 28
Jose
  • 1
  • 1
-1

You can use the HTMLOptionsCollection.namedItem() That means that you have to define your select options to have a name attribute and have the value of the displayed text. e.g California

Jose
  • 1
  • 1