Javascript Beginners – Select a dropdown option by value


A very simple and common issue a Javascript newbie often faces is how to select a dropdown option dynamically by value. People who are working for long with Javascript would solve it in minutes, but hey, this is for a newbie, remember? :)

So this is a simple function I wrote to do the work.

  function selectItemByValue(elmnt, value){

    for(var i=0; i < elmnt.options.length; i++)
    {
      if(elmnt.options[i].value == value)
        elmnt.selectedIndex = i;
    }
  }

Parameters
elmnt: This is the select box taken by functions like "getElementById" or any other way.
value: This is the value which needs to be selected from the options of elmnt.

Example

Lets say you have an HTML select box like below:


<select name="numbers" id="numbers">
<option value="1">One<option>
<option value="2">Two<option>
<option value="3">Three<option>
<option value="4">Four<option>
</select>

I have put an id in the select field to make it easy to get it by ID in a bunch of select fields. What we need to do is, first get the element object and pass it to the function along with the value you want to select. Lets say, we want to select Three. So our Javascript code should look like this:


<script language="javascript">
var number = document.getElementById('numbers');
selectItemByValue(number, 3);
</script>

See it in action









, ,

  1. #1 by R. Hunter on June 24, 2012 - 1:03 pm

    Very nice… especially for long selects. Cheers.

  2. #2 by William on September 12, 2012 - 9:05 pm

    Thank you! Visiting other sites none of them explain that JavaScript simply has an issue with selecting by value and it’s necessary to iterate through all values to find it and select it.

    I just wasn’t sure if I was using .selectedValue the wrong way but appears that can’t be used at all to set.

  3. #3 by Andy Jacobs on March 29, 2014 - 1:39 am

    Hi

    This just saved my life! The only thing I’ve done is change the buttons for images so that people can click on swatches to choose the colour they want as well as using the dropdown.

    Very happy!!!

    Regards
    Andy

  4. #4 by Michael A Griffey on June 24, 2014 - 10:38 pm

    Making 3 simple changes to the code above will give the function a major boost in performance. A difference can really be seen in selects with hundreds of options. Also, we are no longer limited to the number of characters that one may use for identifier names so please everyone stop abbreviating.
    1. If you know none of your options will have a value of null, you can save cycles with a simple null check. The value of the options will never be undefined but the value passed in may be. A simple check here will be more maintainable then placing it everywhere the function is called. if (value !== undefined && value !== null)
    2. It does take a fraction of time to check element.options.length over a constant value. Javascript has no way of knowing you haven’t changed the value in the loop so it must be calculated each time. Assigning var length = element.options.length; will speed things up a bit.
    3. In this scenario, we are dealing with a single selected item. Once the correct value has been identified and selected, there is no need to check the remaining values. Thus, return;.

    function SelectItemByValue(element, value) {
    if (value !== undefined && value !== null) {
    var length = element.options.length;
    for (var i = 0; i < length; i++) {
    if (element.options[i].value === value) {
    element.selectedIndex = i;
    return;
    }
    }
    }
    }

  5. #5 by Alex on November 28, 2014 - 1:17 am

    Not sure if I’m totally wrong here, but the second parameter you’re passing is a number, while you test for the options value at if(elmnt.options[i].value == value). Or in other words: if (“green” == 2).
    At least that’s what I understand from Firefox’ debugger. What’s my mistake?

  6. #6 by Sherif Omran on April 13, 2015 - 1:02 am

    No need for this, there is an easier method

    Example

    TRUE
    FALSE

    Set the value this way

    document.getElementById(“TESTVALUE”).value = “TRUE”;

    if u load the value from php then use this

    document.getElementById(“TESTVALUE”).value = “”;

    This works in Firefox/Safari as far as i checked them. the only concern is that the value TRUE that will be set but be exactly written as in the select

  7. #7 by ชุดเด็ก on February 23, 2016 - 7:58 pm

    ที่อื่นๆการงานของใช้เธอมักจะ
    ชุดเด็ก จะสัมผัสยึดถือคล้ายครัดเคร่งโปรใหญ่โตลำคอล
    ชุดเด็ก ทางการจังหวัดแต่ทว่านางงามบรรยายเหมาเจ้าหล่อนได้คล้องยอม http://www.Happyhappykid.com/ แบ่งออกตนเองโปร่งดั่งสนิทสนมในสื่อเข้าสังคม ชุดเด็ก ค่อนข้างโพสต์รูปข้าวของงานเคลื่อนสิ่งของเธอและผู้มีชีวิตทำเนียบเธอจัดหามาค้นพบด้วยกันจนกระทั่ง

  8. #8 by ganesh on March 11, 2016 - 7:21 pm

    really nice, thank you very much

  9. #9 by javascriptstutorial on May 25, 2016 - 6:55 pm

    Refer this article which have explained how to Select a dropdown element using javascript

  10. #10 by javascriptstutorial on May 25, 2016 - 6:58 pm

    Refer this article which have explained how to Select a dropdown element using JavaScript and Jquery

  11. #12 by m88bet on June 6, 2016 - 4:08 am

    I have to thank you for the efforts you have put in penning this blog.
    I am hoping to see the same high-grade blog posts from you in the future
    as well. In fact, your creative writing abilities has inspired me to get my own, personal website now 😉

  12. #13 by 看護のお仕事 on August 11, 2016 - 5:27 am

    いつもお世話になります。論文実に気付きになりました。また最新記事を期待しています。これからもよろしくお願いします。

    看護士のお仕事は大変な役割です。だからこそ大変で働く人が多いのがホントです。自らの専門看護師としての力をパワーアップしたいと考えたり、プライベートの変動で辞める方が多くいます。こんなナースが復職に成功するには、懸命に求職動くことがポイントですよね。

    さらに詳細な情報は以下のブログを見てください。

  13. #14 by yahoo on August 14, 2016 - 10:16 am

    Thanks a lot for sharing this with all of us you really realize what you’re speaking approximately!
    Bookmarked. Kindly additionally seek advice from my web site
    =). We may have a hyperlink trade arrangement between us

  14. #15 by lettore blu ray portatile on February 12, 2017 - 3:46 am

    Do you have any video of that? I’d want to find out more details.

  15. #16 by Swapnil K on March 9, 2017 - 12:43 pm

    Hi, I am getting error as “JavaScript runtime error: Unable to get property ‘options’ of undefined or null reference” .Pls help

  16. #17 by Swapnil K on March 9, 2017 - 12:45 pm

    I have asp.net dropdown control inside gridview.

(will not be published)