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

Multi tool use


How do I programmatically set the value of a select box element using JavaScript?
I have the following HTML <select>
element:
<select>
<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?
leaveCode
Check out this : javascriptstutorial.com/blog/…
– user5846985
May 25 '16 at 19:16
15 Answers
15
SelectElement("leaveCode", valueToSelect)
function SelectElement(id, valueToSelect)
{
var element = document.getElementById(id);
element.value = valueToSelect;
}
I know that it works in IE, FF, and Safari. Where doesn't it work?
– Mitchel Sellers
Sep 17 '08 at 5:57
Great answer, this is way easier than looping through the options. And it's standards compliant: dev.w3.org/html5/spec/…. 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
Older versions of IE. But it does not matter now, it's 2012.
– Milan Babuškov
Nov 15 '12 at 10:54
And what about multiple selects? This doesn't seem to work in case of multiple options (at least in Chrome 25).
– Georgii Ivankin
Mar 4 '13 at 16:13
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 4:55
If you are using jQuery you can also do this
$('#leaveCode').val('14');
This will select the option with the value of 14
Edit:
With plain Javascript, this can also be achieved with two Document methods
with querySelector, you can select an element based on CSS selector
document.querySelector('#leaveCode').value = '14'
Or the more established approach, with getDocumentById, that will, as the name of the function implies, let you select an element based on there id
id
document.getElementById('leaveCode').value = '14'
You can run the bellow 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>
Nice way of doing it, especially on pages where you're already using jQuery.
– Ectropy
Aug 7 '15 at 14:25
This can also be used for multi-select; just pass an array of strings to the 'val' function instead of a single string. See: 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
$("#leaveCode").val("14").change();
– Loren
Jun 19 '17 at 19:28
function setSelectValue (id, val) {
document.getElementById(id).value = val;
}
setSelectValue('leaveCode', 14);
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;
Shouldn't formObj.leaveCode[i].selected = true; be formObj.options[i].selected = true; ?
– David Christopher Reynolds
Oct 3 '17 at 9:58
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
One wonders what kind of selects need more than the number of countries in a normal country select
– mplungjan
Dec 30 '12 at 10:56
excuse me, about what kind of country select are you talking about?
– Toskan
Jan 2 '13 at 10:56
I give you an example: your colleagues. As an admin you have 8000 colleagues, as normal worker you have ~10. Furthermore: implementing a filtering mechanism only makes sense, when the extra effort is worth it. E.g. an element which is used twice a month should not be wasted time on, to save 2 seconds.
– Toskan
Jan 2 '13 at 12:51
That is what autocomplete is for. Anyway our 8000 person phonebook does not have drop downs at all and can be sorted and searched on without using a drop down. Just my $.02
– mplungjan
Jan 2 '13 at 13:30
Well the autocomplete in our case is built on top of the select list. The advantage is you don't have to program anything, you just reuse it. If the select would be important or used often, a autocomplete with full ajax support is probably what you want. But as this is not the case for all select lists, I'm sure there is something more important to improve ;-)
– Toskan
Jan 2 '13 at 14:02
document.getElementById('leaveCode').value = '10';
That should set the selection to "Annual Leave"
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();
function foo(value)
{
var e = document.getElementById('leaveCode');
if(e) e.value = 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.
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;
}
Suppose your form is named form1:
function selectValue(val)
{
var lc = document.form1.leaveCode;
for (i=0; i<lc.length; i++)
{
if (lc.options[i].value == val)
{
lc.selectedIndex = i;
return;
}
}
}
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;
}
There are different ways to Select values of drop down using Javascript.
You most likely want this:
$("._statusDDL").val('2');
OR
$('select').prop('selectedIndex', 3);
This is assuming the OP is using JQuery though
– Barry Michael Doyle
Dec 3 '16 at 8:00
@BarryMichaelDoyle, Which is not, because even the title of the questions ends with
using JavaScript
.– Iulian Onofrei
Jan 25 at 16:14
using JavaScript
You know this isn't my answer right? That's why I made the comment...
– Barry Michael Doyle
Jan 26 at 7:42
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>';
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
The 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
select()
selected
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?
see my answer for a comparison of performance for different methods
– Toskan
Aug 10 '12 at 15:53