[javascript] How do I programmatically set the value of a select box element using JavaScript?

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?

This question is related to javascript html dom

The answer is


You can use this function:

selectElement('leaveCode', '11')

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

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;
}


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


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.


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;
}

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;
}

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;

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;
    }
  }
}

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;

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;
}

document.getElementById('leaveCode').value = '10';

That should set the selection to "Annual Leave"


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!


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>';


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


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;

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>';

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;
}

document.getElementById('leaveCode').value = '10';

That should set the selection to "Annual Leave"


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.


function setSelectValue (id, val) {
    document.getElementById(id).value = val;
}
setSelectValue('leaveCode', 14);

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


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;
}

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();

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


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.


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.


function setSelectValue (id, val) {
    document.getElementById(id).value = val;
}
setSelectValue('leaveCode', 14);

document.getElementById('leaveCode').value = '10';

That should set the selection to "Annual Leave"


You most likely want this:

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

OR

$('select').prop('selectedIndex', 3); 

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;
}

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!



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


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;
    }
  }
}


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


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:

_x000D_
_x000D_
const jQueryFunction = () => {_x000D_
  _x000D_
  $('#leaveCode').val('14'); _x000D_
  _x000D_
}_x000D_
_x000D_
const querySelectorFunction = () => {_x000D_
  _x000D_
  document.querySelector('#leaveCode').value = '14' _x000D_
  _x000D_
}_x000D_
_x000D_
const getElementByIdFunction = () => {_x000D_
  _x000D_
  document.getElementById('leaveCode').value='14' _x000D_
  _x000D_
}
_x000D_
input {_x000D_
  display:block;_x000D_
  margin: 10px;_x000D_
  padding: 10px_x000D_
}
_x000D_
<select id="leaveCode" name="leaveCode">_x000D_
  <option value="10">Annual Leave</option>_x000D_
  <option value="11">Medical Leave</option>_x000D_
  <option value="14">Long Service</option>_x000D_
  <option value="17">Leave Without Pay</option>_x000D_
</select>_x000D_
_x000D_
<input type="button" value="$('#leaveCode').val('14');" onclick="jQueryFunction()" />_x000D_
<input type="button" value="document.querySelector('#leaveCode').value = '14'" onclick="querySelectorFunction()" />_x000D_
<input type="button" value="document.getElementById('leaveCode').value = '14'" onclick="getElementByIdFunction()" />_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_


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;

function setSelectValue (id, val) {
    document.getElementById(id).value = val;
}
setSelectValue('leaveCode', 14);

shortest

This is size improvement of William answer

leaveCode.value = '14';

_x000D_
_x000D_
leaveCode.value = '14';
_x000D_
<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>
_x000D_
_x000D_
_x000D_


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


You most likely want this:

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

OR

$('select').prop('selectedIndex', 3); 

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();

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;
    }
  }
}

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


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;
}

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:

_x000D_
_x000D_
const jQueryFunction = () => {_x000D_
  _x000D_
  $('#leaveCode').val('14'); _x000D_
  _x000D_
}_x000D_
_x000D_
const querySelectorFunction = () => {_x000D_
  _x000D_
  document.querySelector('#leaveCode').value = '14' _x000D_
  _x000D_
}_x000D_
_x000D_
const getElementByIdFunction = () => {_x000D_
  _x000D_
  document.getElementById('leaveCode').value='14' _x000D_
  _x000D_
}
_x000D_
input {_x000D_
  display:block;_x000D_
  margin: 10px;_x000D_
  padding: 10px_x000D_
}
_x000D_
<select id="leaveCode" name="leaveCode">_x000D_
  <option value="10">Annual Leave</option>_x000D_
  <option value="11">Medical Leave</option>_x000D_
  <option value="14">Long Service</option>_x000D_
  <option value="17">Leave Without Pay</option>_x000D_
</select>_x000D_
_x000D_
<input type="button" value="$('#leaveCode').val('14');" onclick="jQueryFunction()" />_x000D_
<input type="button" value="document.querySelector('#leaveCode').value = '14'" onclick="querySelectorFunction()" />_x000D_
<input type="button" value="document.getElementById('leaveCode').value = '14'" onclick="getElementByIdFunction()" />_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_


shortest

This is size improvement of William answer

leaveCode.value = '14';

_x000D_
_x000D_
leaveCode.value = '14';
_x000D_
<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>
_x000D_
_x000D_
_x000D_


document.getElementById('leaveCode').value = '10';

That should set the selection to "Annual Leave"


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to dom

How do you set the document title in React? How to find if element with specific id exists or not Cannot read property 'style' of undefined -- Uncaught Type Error adding text to an existing text element in javascript via DOM Violation Long running JavaScript task took xx ms How to get `DOM Element` in Angular 2? Angular2, what is the correct way to disable an anchor element? React.js: How to append a component on click? Detect click outside React component DOM element to corresponding vue.js component