604

I have the following HTML <select> element:

<select id="leaveCode" name="leaveCode">
  <option value="10">Annual Leave</option>
  <option value="11">Medical Leave</option>
  <option value="14">Long Service</option>
  <option value="17">Leave Without Pay</option>
</select>

Using a JavaScript function with the leaveCode number as a parameter, how do I select the appropriate option in the list?

Brett DeWoody
  • 59,771
  • 29
  • 135
  • 184
brasskazoo
  • 76,030
  • 23
  • 64
  • 76

17 Answers17

755

You can use this function:

function selectElement(id, valueToSelect) {    
    let element = document.getElementById(id);
    element.value = valueToSelect;
}

selectElement('leaveCode', '11');
<select id="leaveCode" name="leaveCode">
  <option value="10">Annual Leave</option>
  <option value="11">Medical Leave</option>
  <option value="14">Long Service</option>
  <option value="17">Leave Without Pay</option>
</select>

Optionally if you want to trigger onchange event also, you can use :

element.dispatchEvent(new Event('change'))
Lee Taylor
  • 7,761
  • 16
  • 33
  • 49
Mitchel Sellers
  • 62,228
  • 14
  • 110
  • 173
  • 4
    Great answer, this is way easier than looping through the options. And it's standards compliant: http://dev.w3.org/html5/spec/the-select-element.html#the-select-element. If there are browser incompatibilities (of course there are :) I'd be very interested to know what they are. That's the sort of thing you usually count on ppk for, but he stubbornly refuses to show up in my searches for this topic. – philo May 22 '12 at 17:47
  • @Milan Maybe the cross browser issue is when *valueToSelect* does not exist in the Select Options, where browsers may behave differently (like 1.do not change current value, or 2.set value to null, or 3.force value to be that one anyway...)? I didn't try myself, just wondering. – Déjà vu Nov 14 '12 at 05:34
  • 11
    And what about multiple selects? This doesn't seem to work in case of multiple options (at least in Chrome 25). – Georgii Ivankin Mar 04 '13 at 16:13
  • Important to note that this does not actually reflect the HTML `value=""` attribute. ` – mastaBlasta Feb 07 '14 at 19:49
  • 3
    As @ring0 pointed out, when valueToSelect does not exist, it inserts a blank entry in chrome. whereas IE and firefox retains the last selected value. – Karthik Bose Jun 24 '15 at 04:55
  • 1
    Note for IE : the as a valueToSelect – Peter Quiring May 18 '16 at 13:58
  • Side note - in chrome, a hidden field will not have it's value changed dynamically so it must be visible and/or display != none; – Patrick Sturm Nov 30 '18 at 11:59
  • 20
    If you need the change event to be fired, you should also do: `element.dispatchEvent(new Event('change'));` – Patrick James McDougle Feb 08 '19 at 20:13
152

If you are using jQuery you can also do this:

$('#leaveCode').val('14');

This will select the <option> with the value of 14.


With plain Javascript, this can also be achieved with two Document methods:

  • With document.querySelector, you can select an element based on a CSS selector:

    document.querySelector('#leaveCode').value = '14'
    
  • Using the more established approach with document.getElementById(), that will, as the name of the function implies, let you select an element based on its id:

    document.getElementById('leaveCode').value = '14'
    

You can run the below code snipped to see these methods and the jQuery function in action:

const jQueryFunction = () => {
  
  $('#leaveCode').val('14'); 
  
}

const querySelectorFunction = () => {
  
  document.querySelector('#leaveCode').value = '14' 
  
}

const getElementByIdFunction = () => {
  
  document.getElementById('leaveCode').value='14' 
  
}
input {
  display:block;
  margin: 10px;
  padding: 10px
}
<select id="leaveCode" name="leaveCode">
  <option value="10">Annual Leave</option>
  <option value="11">Medical Leave</option>
  <option value="14">Long Service</option>
  <option value="17">Leave Without Pay</option>
</select>

<input type="button" value="$('#leaveCode').val('14');" onclick="jQueryFunction()" />
<input type="button" value="document.querySelector('#leaveCode').value = '14'" onclick="querySelectorFunction()" />
<input type="button" value="document.getElementById('leaveCode').value = '14'" onclick="getElementByIdFunction()" />

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
a stone arachnid
  • 1,272
  • 1
  • 15
  • 27
Einar Ólafsson
  • 3,036
  • 1
  • 19
  • 24
  • 5
    This can also be used for multi-select; just pass an array of strings to the 'val' function instead of a single string. See: http://stackoverflow.com/a/16583001/88409 – Triynko Dec 22 '15 at 21:38
  • Is there a way to also trigger $('#leaveCode').on('change', function() by doing that? – Lieuwe Nov 24 '16 at 16:56
  • 12
    $("#leaveCode").val("14").change(); – Loren Jun 19 '17 at 19:28
32
function setSelectValue (id, val) {
    document.getElementById(id).value = val;
}
setSelectValue('leaveCode', 14);
Andrew Hedges
  • 21,688
  • 16
  • 67
  • 79
23

Not answering the question, but you can also select by index, where i is the index of the item you wish to select:

var formObj = document.getElementById('myForm');
formObj.leaveCode[i].selected = true;

You can also loop through the items to select by display value with a loop:

for (var i = 0, len < formObj.leaveCode.length; i < len; i++) 
    if (formObj.leaveCode[i].value == 'xxx') formObj.leaveCode[i].selected = true;
Chase Seibert
  • 15,703
  • 8
  • 51
  • 58
17

I compared the different methods:

Comparison of the different ways on how to set a value of a select with JS or jQuery

code:

$(function() {
    var oldT = new Date().getTime();
     var element = document.getElementById('myId');
    element.value = 4;
    console.error(new Date().getTime() - oldT);

    oldT = new Date().getTime();
    $("#myId option").filter(function() {
        return $(this).attr('value') == 4;
    }).attr('selected', true);
    console.error(new Date().getTime() - oldT);

    oldT = new Date().getTime();
    $("#myId").val("4");
    console.error(new Date().getTime() - oldT);
});

Output on a select with ~4000 elements:

  • 1 ms
  • 58 ms
  • 612 ms

With Firefox 10. Note: The only reason I did this test, was because jQuery performed super poorly on our list with ~2000 entries (they had longer texts between the options). We had roughly 2 s delay after a val()

Note as well: I am setting value depending on the real value, not the text value.

awran5
  • 4,333
  • 2
  • 15
  • 32
Toskan
  • 13,911
  • 14
  • 95
  • 185
16

Short

This is size improvement of William answer

leaveCode.value = '14';

leaveCode.value = '14';
<select id="leaveCode" name="leaveCode">
  <option value="10">Annual Leave</option>
  <option value="11">Medical Leave</option>
  <option value="14">Long Service</option>
  <option value="17">Leave Without Pay</option>
</select>
Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
  • 3
    Shouldn't this use a jquery selector or something? Or am I just slow this morning and one can simply call some_id.value in js? – logicOnAbstractions Aug 19 '21 at 16:08
  • 3
    this should be the accepted answer! – Les Nightingill Dec 16 '21 at 20:36
  • @logicOnAbstractions yes it turns out one can simply call `some_id.value` in browser JS instead of `document.getElementByID("some_id").value`, though you probably shouldn't. Discussion here: https://stackoverflow.com/questions/25325221/why-dont-we-just-use-element-ids-as-identifiers-in-javascript It looks like it's a very old feature that was kept for backward compatibility. It's very tempting to use it since it's so much briefer and prettier... – Kai Carver May 25 '23 at 14:57
13

I tried the above JavaScript/jQuery-based solutions, such as:

$("#leaveCode").val("14");

and

var leaveCode = document.querySelector('#leaveCode');
leaveCode[i].selected = true;

in an AngularJS app, where there was a required <select> element.

None of them works, because the AngularJS form validation is not fired. Although the right option was selected (and is displayed in the form), the input remained invalid (ng-pristine and ng-invalid classes still present).

To force the AngularJS validation, call jQuery change() after selecting an option:

$("#leaveCode").val("14").change();

and

var leaveCode = document.querySelector('#leaveCode');
leaveCode[i].selected = true;
$(leaveCode).change();
lumi77
  • 247
  • 2
  • 4
  • Why use jQuery for this when you can already do it with Angular? When using Angular itself, don't you have the ability to set the value, with built-in support for triggering the change (No idea, I use React, just found this post after a 5 second google: https://stackoverflow.com/questions/50302062/angular-5-set-selected-value-of-html-select-element)? Because that would mean you don't have to hack around Angular with an additional ±30kb library "just for this" :) – SidOfc Jun 12 '19 at 10:02
13
document.getElementById('leaveCode').value = '10';

That should set the selection to "Annual Leave"

William
  • 6,338
  • 4
  • 32
  • 36
4

The easiest way if you need to:
1) Click a button which defines select option
2) Go to another page, where select option is
3) Have that option value selected on another page

1) your button links (say, on home page)

<a onclick="location.href='contact.php?option=1';" style="cursor:pointer;">Sales</a>
<a onclick="location.href='contact.php?option=2';" style="cursor:pointer;">IT</a>

(where contact.php is your page with select options. Note the page url has ?option=1 or 2)

2) put this code on your second page (my case contact.php)

<?
if (isset($_GET['option']) && $_GET['option'] != "") {
$pg = $_GET['option'];              
} ?>

3) make the option value selected, depending on the button clicked

<select>
<option value="Sales" <? if ($pg == '1') { echo "selected"; } ?> >Sales</option>
<option value="IT" <? if ($pg == '2') { echo "selected"; } ?> >IT</option>
</select>

.. and so on.
So this is an easy way of passing the value to another page (with select option list) through GET in url. No forms, no IDs.. just 3 steps and it works perfect.

Lana
  • 73
  • 1
  • 1
3

function foo(value)
{
    var e = document.getElementById('leaveCode');
    if(e) e.value = value;
}

mmattax
  • 27,172
  • 41
  • 116
  • 149
2

Should be something along these lines:

function setValue(inVal){
var dl = document.getElementById('leaveCode');
var el =0;
for (var i=0; i<dl.options.length; i++){
  if (dl.options[i].value == inVal){
    el=i;
    break;
  }
}
dl.selectedIndex = el;
}
BeniBela
  • 16,412
  • 4
  • 45
  • 52
Stephen Wrighton
  • 36,783
  • 6
  • 67
  • 86
2

Suppose your form is named form1:

function selectValue(val)
{
  var lc = document.form1.leaveCode;
  for (i=0; i&lt;lc.length; i++)
  {
    if (lc.options[i].value == val)
    {
        lc.selectedIndex = i;
        return;
    }
  }
}
Milan Babuškov
  • 59,775
  • 49
  • 126
  • 179
1

Why not add a variable for the element's Id and make it a reusable function?

function SelectElement(selectElementId, valueToSelect)
{    
    var element = document.getElementById(selectElementId);
    element.value = valueToSelect;
}
Robert Swisher
  • 1,300
  • 11
  • 12
0

Most of the code mentioned here didn't worked for me!

At last, this worked

window.addEventListener is important, otherwise, your JS code will run before values are fetched in the Options

    window.addEventListener("load", function () {
            // Selecting Element with ID - leaveCode  //
            var formObj = document.getElementById('leaveCode');

            // Setting option as selected
            let len;
            for (let i = 0, len = formObj.length; i < len; i++){
                if (formObj[i].value == '<value to show in Select>') 
                 formObj.options[i].selected = true;
            }
    });

Hope, this helps!

Ashutosh Tiwari
  • 1,496
  • 11
  • 20
-2

You most likely want this:

$("._statusDDL").val('2');

OR

$('select').prop('selectedIndex', 3); 
Makyen
  • 31,849
  • 12
  • 86
  • 121
-3

If using PHP you could try something like this:

$value = '11';
$first = '';
$second = '';
$third = '';
$fourth = '';

switch($value) {
            case '10' :
                $first = 'selected';
            break;
            case '11' :
                $second = 'selected';
            break;
            case '14' :
                $third = 'selected';
            break;
            case '17' :
                $fourth = 'selected';
            break;
        }

echo'
<select id="leaveCode" name="leaveCode">
  <option value="10" '. $first .'>Annual Leave</option>
  <option value="11" '. $second .'>Medical Leave</option>
  <option value="14" '. $third .'>Long Service</option>
  <option value="17" '. $fourth .'>Leave Without Pay</option>
</select>';
almyz125
  • 648
  • 1
  • 7
  • 18
-6

I'm afraid I'm unable to test this at the moment, but in the past, I believe I had to give each option tag an ID, and then I did something like:

document.getElementById("optionID").select();

If that doesn't work, maybe it'll get you closer to a solution :P

Lucas Oman
  • 15,597
  • 2
  • 44
  • 45
  • 3
    The [HTMLOptionElement](https://developer.mozilla.org/en/DOM/HTMLOptionElement) does not have a `select()` method (it does not define any additional methods over the standard set on all HTML elements). However, you can set the `selected` property to true. – MrWhite Mar 28 '12 at 11:35