238

I have option menu like this:

<form name="AddAndEdit">
   <select name="list" id="personlist">
      <option value="11">Person1</option>
      <option value="27">Person2</option>
      <option value="17">Person3</option>
      <option value="10">Person4</option>
      <option value="7">Person5</option>
      <option value="32">Person6</option>
      <option value="18">Person7</option>
      <option value="29">Person8</option>
      <option value="28">Person9</option>
      <option value="34">Person10</option>
      <option value="12">Person11</option>
      <option value="19">Person12</option>
   </select>
</form>

And now I want to change the selected option by using an href. For example:

<a href="javascript:void(0);"
  onclick="document.getElementById('personlist').getElementsByTagName('option')[11].selected = 'selected';">change</a>

But I want to select the option with value=11 (Person1), not Person12.

How do I change this code?

ˈvɔlə
  • 7,697
  • 8
  • 56
  • 77
breq
  • 22,854
  • 23
  • 60
  • 102

11 Answers11

289

Change

document.getElementById('personlist').getElementsByTagName('option')[11].selected = 'selected'

to

document.getElementById('personlist').value=Person_ID;
Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
breq
  • 22,854
  • 23
  • 60
  • 102
  • 1
    how does this work with multiple values? For example: `document.getElementById('personlist').value=id1,id2` will not work, how to manage that? – utdev Mar 17 '17 at 11:30
  • 4
    @utdev here is a solution for multiple selecting http://stackoverflow.com/a/1296068/1251563 tip: you need to use a loop – breq Mar 17 '17 at 11:44
  • So I can't do something like `.value = id1, id2` or `.value = [array]` ? – utdev Mar 17 '17 at 11:50
  • @utdev unfortunately no... You need to use a loop – breq Mar 17 '17 at 11:53
  • Also you can get value through select options without setting the class like `var id = document.getElementById('personlist').value`. I used in different answer, thanks anyway! – Alper Feb 06 '19 at 08:52
64

Tools as pure JavaScript code for handling Selectbox:

Graphical Understanding:

Image - A

enter image description here


Image - B

enter image description here


Image - C

enter image description here

Updated - 25-June-2019 | Fiddler DEMO

JavaScript Code:

/**
 * Empty Select Box
 * @param eid Element ID
 * @param value text
 * @param text text
 * @author Neeraj.Singh
 */
function emptySelectBoxById(eid, value, text) {
    document.getElementById(eid).innerHTML = "<option value='" + value + "'>" + text + "</option>";
}


/**
 * Reset Select Box
 * @param eid Element ID
 */

function resetSelectBoxById(eid) {
    document.getElementById(eid).options[0].selected = 'selected';
}


/**
 * Set Select Box Selection By Index
 * @param eid Element ID
 * @param eindx Element Index
 */

function setSelectBoxByIndex(eid, eindx) {
    document.getElementById(eid).getElementsByTagName('option')[eindx].selected = 'selected';
    //or
    document.getElementById(eid).options[eindx].selected = 'selected';
}


/**
 * Set Select Box Selection By Value
 * @param eid Element ID
 * @param eval Element Index
 */
function setSelectBoxByValue(eid, eval) {
    document.getElementById(eid).value = eval;
}


/**
 * Set Select Box Selection By Text
 * @param eid Element ID
 * @param eval Element Index
 */
function setSelectBoxByText(eid, etxt) {
    var eid = document.getElementById(eid);
    for (var i = 0; i < eid.options.length; ++i) {
        if (eid.options[i].text === etxt)
            eid.options[i].selected = true;
    }
}


/**
 * Get Select Box Text By ID
 * @param eid Element ID
 * @return string
 */

function getSelectBoxText(eid) {
    return document.getElementById(eid).options[document.getElementById(eid).selectedIndex].text;
}


/**
 * Get Select Box Value By ID
 * @param eid Element ID
 * @return string
 */

function getSelectBoxValue(id) {
    return document.getElementById(id).options[document.getElementById(id).selectedIndex].value;
}
Nono
  • 6,468
  • 3
  • 35
  • 37
  • 2
    Great example on how to interact with a select with pure javascript! – Mr.GT Mar 26 '14 at 13:49
  • 1
    Link to "Fiddler Demo" now results in 404/Page Not Found :-( – Genki Aug 11 '18 at 04:47
  • 2
    The question is "How do I change an HTML selected option using JavaScript?". You just copy/paste a piece of code without answering nothing. – Thomas Jun 22 '19 at 17:43
35
mySelect.value = myValue;

Where mySelect is your selection box, and myValue is the value you want to change it to.

Toastrackenigma
  • 6,303
  • 4
  • 39
  • 52
Ronnie Royston
  • 13,836
  • 5
  • 66
  • 83
  • Why didn't everyone vote this, is this a new feature? I only need to support recent browsers though so going with this anyhow. – antont Nov 14 '18 at 11:17
  • I always had the notion that you couldn't do this, so I just kinda ignored it. But when I saw this answer, I tried it, and lo and behold, it works just like inputs. This has to be the right answer. +1 – Jaden Baptista Mar 22 '21 at 20:52
32

I believe that the blog post JavaScript Beginners – Select a dropdown option by value might help you.

<a href="javascript:void(0);" onclick="selectItemByValue(document.getElementById('personlist'),11)">change</a>

function selectItemByValue(elmnt, value){

  for(var i=0; i < elmnt.options.length; i++)
  {
    if(elmnt.options[i].value === value) {
      elmnt.selectedIndex = i;
      break;
    }
  }
}
Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
Nick
  • 1,747
  • 3
  • 21
  • 32
27

You could also change select.options.selectedIndex DOM attribute like this:

function selectOption(index){ 
  document.getElementById("select_id").options.selectedIndex = index;
}
<p>
<select id="select_id">
  <option selected>first option</option>
  <option>second option</option>
  <option>third option</option>
</select>
</p>
<p>
  <button onclick="selectOption(0);">Select first option</button>
  <button onclick="selectOption(1);">Select second option</button>
  <button onclick="selectOption(2);">Select third option</button>
</p>
caspinos
  • 401
  • 4
  • 10
5

You can use JQuery also

$(document).ready(function () {
  $('#personlist').val("10");
}
Hossein Golshani
  • 1,813
  • 5
  • 15
  • 26
4

Your own answer technically wasn't incorrect, but you got the index wrong since indexes start at 0, not 1. That's why you got the wrong selection.

document.getElementById('personlist').getElementsByTagName('option')[**10**].selected = 'selected';

Also, your answer is actually a good one for cases where the tags aren't entirely English or numeric.

If they use, for example, Asian characters, the other solutions telling you to use .value() may not always function and will just not do anything. Selecting by tag is a good way to ignore the actual text and select by the element itself.

Cake Princess
  • 109
  • 1
  • 7
3

If you are adding the option with javascript

function AddNewOption(userRoutes, text, id) 
{
    var option = document.createElement("option");
    option.text = text;
    option.value = id;
    option.selected = "selected";
    userdRoutes.add(option);
}
Frank M
  • 59
  • 4
2

An array Index will start from 0. If you want value=11 (Person1), you will get it with position getElementsByTagName('option')[10].selected.

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
Rachana
  • 121
  • 1
  • 9
1

It's an old post, but if anyone is still looking for solution to this kind of problem, here is what I came up with:

<script>
  document.addEventListener("DOMContentLoaded", function(e) {
    document.forms['AddAndEdit'].elements['list'].value = 11;
  });
</script>
Tariqul Islam
  • 347
  • 5
  • 16
0

Note: Option Index count starts from 0. That means first option will be indexed at 0.

document.querySelector(".add__btn").addEventListener("click", function(){
  var index = 1; /*change option value here*/  document.querySelector(".add__type").options.selectedIndex = index;
  document.querySelector(".add__description").value = "Option Index";
  document.querySelector(".add__value").value = index;
});
<html>
    <div class="add__container">
         <select class="add__type">
            <option value="inc" selected>+</option>
            <option value="exp">-</option>
         </select>
         <input type="text" class="add__description" placeholder="Add description">
         <input type="number" class="add__value" placeholder="Value">
         <button class="add__btn"> Submit </button>
</div>

<h4> Default Option Value will be selected after pressing Submit </h4>