46

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...

1
  • The loop is working, but I wonder is there any way I can do it without a loop? And also, no jQuery? Commented Jun 2, 2011 at 4:44

7 Answers 7

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;
        }
    }
}
Sign up to request clarification or add additional context in comments.

4 Comments

No loop, no jQuery, is it possible?
Why do you use that j there?
@JuanLuisSoldi So I don't recalculate sel.options.length more times than I absolutely have to.
@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.
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/)

4 Comments

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...
actually this loop is effective because as soon as the condition is met, the loop stops. thats why i use the break; command
A while ago, I can't (not enough reputation). But now you commented, I gained reputation or privileges rather, I voted your answer up.
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
4

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

1 Comment

Could just use CSS selector select#animals > option[value="frog"] and save yourself a few lines.
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;
      }     
    }
}

3 Comments

could have cached the document.getElementById :)
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...
@naveen, true, now applied to be neater ;)
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..

Comments

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.

Comments

-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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.