174

In my HTML, I have a <select> with three <option> elements. I want to use jQuery to check each option's value against a Javascript var. If one matches, I want to set the selected attribute of that option. How would I do that?

alex
  • 6,818
  • 9
  • 52
  • 103
llihttocs
  • 2,001
  • 3
  • 14
  • 10

14 Answers14

377

Vanilla JavaScript

Using plain old JavaScript:

var val = "Fish";
var sel = document.getElementById('sel');
document.getElementById('btn').onclick = function() {
  var opts = sel.options;
  for (var opt, j = 0; opt = opts[j]; j++) {
    if (opt.value == val) {
      sel.selectedIndex = j;
      break;
    }
  }
}
<select id="sel">
    <option>Cat</option>
    <option>Dog</option>
    <option>Fish</option>
</select>
<button id="btn">Select Fish</button>

jQuery

But if you really want to use jQuery:

var val = 'Fish';
$('#btn').on('click', function() {
  $('#sel').val(val);
});

var val = 'Fish';
$('#btn').on('click', function() {
  $('#sel').val(val);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id="sel">
    <option>Cat</option>
    <option>Dog</option>
    <option>Fish</option>
</select>
<button id="btn">Select Fish</button>

jQuery - Using Value Attributes

In case your options have value attributes which differ from their text content and you want to select via text content:

<select id="sel">
    <option value="1">Cat</option>
    <option value="2">Dog</option>
    <option value="3">Fish</option>
</select>
<script>
    var val = 'Fish';
    $('#sel option:contains(' + val + ')').prop({selected: true});
</script>

Demo

But if you do have the above set up and want to select by value using jQuery, you can do as before:

var val = 3;
$('#sel').val(val);

Modern DOM

For the browsers that support document.querySelector and the HTMLOptionElement::selected property, this is a more succinct way of accomplishing this task:

var val = 3;    
document.querySelector('#sel [value="' + val + '"]').selected = true;

Demo

Knockout.js

<select data-bind="value: val">
    <option value="1">Cat</option>
    <option value="2">Dog</option>
    <option value="3">Fish</option>
</select>
<script>
    var viewModel = {
        val: ko.observable()
    };
    ko.applyBindings(viewModel);
    viewModel.val(3);
</script>

Demo

Polymer

<template id="template" is="dom-bind">
    <select value="{{ val }}">
        <option value="1">Cat</option>
        <option value="2">Dog</option>
        <option value="3">Fish</option>
    </select>
</template>
<script>
    template.val = 3;
</script>

Demo

Angular 2

Note: this has not been updated for the final stable release.

<app id="app">
    <select [value]="val">
        <option value="1">Cat</option>
        <option value="2">Dog</option>
        <option value="3">Fish</option>
    </select>
</app>
<script>
    var App = ng.Component({selector: 'app'})
        .View({template: app.innerHTML})
        .Class({constructor:  function() {}});

    ng.bootstrap(App).then(function(app) {
        app._hostComponent.instance.val = 3;
    });
</script>

Demo

Vue 2

<div id="app">
    <select v-model="val">
        <option value="1">Cat</option>
        <option value="2">Dog</option>
        <option value="3">Fish</option>
    </select>
</div>
<script>
    var app = new Vue({
        el: '#app',
        data: {
                val: null,
        },
        mounted: function() {
                this.val = 3;
        }
    });
</script>

Demo

kzh
  • 19,810
  • 13
  • 73
  • 97
  • 1
    This was especially useful because I wasn't sure how to set the selected attribute. I didn't realize there was a selectedIndex. Thanks. – llihttocs Sep 10 '11 at 17:52
  • @llihttocs :-( how about now? – kzh Sep 14 '13 at 22:11
  • 1
    @aelgoa http://jsperf.com/option-select-loop/2 I corrected your first snippet to more mimic my code, which makes mine slower. I used post-increment instead of pre-increment, and then I added another test which is slightly faster than your 3rd test. – kzh Nov 04 '13 at 14:03
  • 1
    for the sadistic: `document.evaluate(".//select[@id='sel']/option[text()='Fish']", document.body, null, 9, null).singleNodeValue.selected = true;` – kzh Jul 22 '14 at 20:14
  • 1
    @llihttocs What about now? – kzh Sep 22 '14 at 22:38
  • @llihttocs I'll try and expand this a little more for you. – kzh Sep 15 '15 at 17:32
  • How to get the change callback to work? – Corey Alix Nov 11 '15 at 14:43
  • @CoreyAlix this is probably suited for another question. Link it here. – kzh Nov 11 '15 at 14:47
  • 1
    Thank you for including vanilla javascript - for those of us who love to code for ourselves :) – Peter Cullen Oct 07 '19 at 02:35
  • Impressive, and especially for showing the principles behind how this works, not just answering the singular question. Thank you. In particular I appreciate the efforts in posting a Vanilla-JS and a "modern" query selector solution. – aaron p Jul 03 '20 at 09:36
27

None of the examples using jquery in here are actually correct as they will leave the select displaying the first entry even though value has been changed.

The right way to select Alaska and have the select show the right item as selected using:

<select id="state">
    <option value="AL">Alabama</option>
    <option value="AK">Alaska</option>
    <option value="AZ">Arizona</option>
</select>

With jquery would be:

$('#state').val('AK').change();
Justin Buser
  • 2,813
  • 25
  • 32
26

You can change the value of the select element, which changes the selected option to the one with that value, using JavaScript:

document.getElementById('sel').value = 'bike';​​​​​​​​​​

DEMO

dlaliberte
  • 3,250
  • 2
  • 25
  • 22
Ivin Raj
  • 3,448
  • 2
  • 28
  • 65
10

Markup

<select id="my_select">
    <option value="1">First</option>
    <option value="2">Second</option>
    <option value="3">Third</option>
</select>

jQuery

var my_value = 2;
$('#my_select option').each(function(){
    var $this = $(this); // cache this jQuery object to avoid overhead

    if ($this.val() == my_value) { // if this option's value is equal to our value
        $this.prop('selected', true); // select this option
        return false; // break the loop, no need to look further
    }
});

Demo

Shef
  • 44,808
  • 15
  • 79
  • 90
  • I think this is exactly what I needed. I have already used several lines of your code and it seems to work. Thanks for the great snippets. – llihttocs Sep 10 '11 at 17:53
  • @llihttocs: Glad I helped. Feel free to accept the answer which solves your problem by clicking the empty tick below the vote count on the top left hand side of the answer. So that this question gets marked as resolved and others who will be looking for the same solution will find the answer easily. – Shef Sep 10 '11 at 17:56
4

I want to change the select element's selected option's both value & textContent (what we see) to 'Mango'.

Simplest code that worked is below:

var newValue1 = 'Mango'

var selectElement = document.getElementById('myselectid');
selectElement.options[selectElement.selectedIndex].value = newValue1;
selectElement.options[selectElement.selectedIndex].textContent = newValue1;
General Grievance
  • 4,555
  • 31
  • 31
  • 45
Manohar Reddy Poreddy
  • 25,399
  • 9
  • 157
  • 140
3

I used almost all of the answers posted here but not comfortable with that so i dig one step furter and found easy solution that fits my need and feel worth sharing with you guys.
Instead of iteration all over the options or using JQuery you can do using core JS in simple steps:

Example

<select id="org_list">
  <option value="23">IBM</option>
  <option value="33">DELL</option>
  <option value="25">SONY</option>
  <option value="29">HP</option>
</select>

So you must know the value of the option to select.

function selectOrganization(id){
    org_list=document.getElementById('org_list');
    org_list.selectedIndex=org_list.querySelector('option[value="'+id+'"]').index;
}

How to Use?

selectOrganization(25); //this will select SONY from option List

Your comments are welcome. :) AzmatHunzai.

Azmat Karim Khan
  • 437
  • 5
  • 18
2

Test this Demo

  1. Selecting Option based on its value

    var vals = [2,'c'];
    
    $('option').each(function(){
       var $t = $(this);
    
       for (var n=vals.length; n--; )
          if ($t.val() == vals[n]){
             $t.prop('selected', true);
             return;
          }
    });
    
  2. Selecting Option based on its text

    var vals = ['Two','CCC'];                   // what we're looking for is different
    
    $('option').each(function(){
       var $t = $(this);
    
       for (var n=vals.length; n--; )
          if ($t.text() == vals[n]){            // method used is different
             $t.prop('selected', true);
             return;
          }
    });
    

Supporting HTML

<select>
   <option value=""></option>
   <option value="1">One</option>
   <option value="2">Two</option>
   <option value="3">Three</option>
</select>

<select>
   <option value=""></option>
   <option value="a">AAA</option>
   <option value="b">BBB</option>
   <option value="c">CCC</option>
</select>
vol7ron
  • 40,809
  • 21
  • 119
  • 172
  • 1
    This example is very useful. I wasn't sure how to iterate through the options and set the selected attribute. Thank you for such a complete answer. – llihttocs Sep 10 '11 at 17:51
  • No problem llihttocs, be sure to click the up arrow next to questions/comments you find helpful. And select the checkmark next to the answer you choose. -- you can do either w/o it costing you anything – vol7ron Sep 10 '11 at 17:59
1

Excellent answers - here's the D3 version for anyone looking:

<select id="sel">
    <option>Cat</option>
    <option>Dog</option>
    <option>Fish</option>
</select>
<script>
    d3.select('#sel').property('value', 'Fish');
</script>
Tristan Reid
  • 5,844
  • 2
  • 26
  • 31
1

After a lot of searching I tried @kzh on select list where I only know option inner text not value attribute, this code based on select answer I used it to change select option according to current page urlon this format http://www.example.com/index.php?u=Steve

<select id="sel">
    <option>Joe</option>
    <option>Steve</option>
    <option>Jack</option>
</select>
<script>
    var val = window.location.href.split('u=')[1]; // to filter ?u= query 
    var sel = document.getElementById('sel');
    var opts = sel.options;
    for(var opt, j = 0; opt = opts[j]; j++) {
        // search are based on text inside option Attr
        if(opt.text == val) {
            sel.selectedIndex = j;
            break;
        }
    }
</script>

This will keeps url parameters shown as selected to make it more user friendly and the visitor knows what page or profile he is currently viewing .

Pyrce
  • 8,296
  • 3
  • 31
  • 46
Salem
  • 654
  • 7
  • 24
1

You just write the code

var theVal = 1;

$('#variable_id').val(theVal).trigger('change');
Pierre-Yves Gillier
  • 507
  • 1
  • 4
  • 17
0

I used this after updating a register and changed the state of request via ajax, then I do a query with the new state in the same script and put it in the select tag element new state to update the view.

var objSel = document.getElementById("selectObj");
objSel.selectedIndex = elementSelected;

I hope this is useful.

Matteo Baldi
  • 5,613
  • 10
  • 39
  • 51
0

selectElement is a html <select> element.

Increment the value:

selectElement.selectedIndex++

Decrement the value:

selectElement.selectedIndex--
NVRM
  • 11,480
  • 1
  • 88
  • 87
0

var accHos = document.getElementById("accHos");
function showName(obj) {
  accHos.selectedIndex = obj.selectedIndex;
 }
div {
  color: coral;
}
select {
  margin-left: 20px;
  margin-bottom:  8px;
  min-width: 120px;
}
<div>Select Account Number:</div>
<select id="accNos" name="" onchange="showName(this);">
  <option value="">Select Account</option>
  <option value="">1052021</option>
  <option value="">2052021</option>
  <option value="">3052021</option>
  <option value="">4052021</option>
  <option value="">5052021</option>
</select>

<div>Account Holder Name:</div>
<select id="accHos" name="" disabled>
  <option value="">--Name--</option>
  <option value="">Suhan</option>
  <option value="">Cesur</option>
  <option value="">Hopper</option>
  <option value="">Rachel</option>
  <option value="">Arya</option>
 </select>
 <!-- Just for  my referece -->
Sachin Chillal
  • 393
  • 4
  • 6
-1

Slightly neater Vanilla.JS version. Assuming you've already fixed nodeList missing .forEach():

NodeList.prototype.forEach = Array.prototype.forEach

Just:

var requiredValue = 'i-50332a31',   
  selectBox = document.querySelector('select')

selectBox.childNodes.forEach(function(element, index){
  if ( element.value === requiredValue ) {
    selectBox.selectedIndex = index
  }
})
mikemaccana
  • 110,530
  • 99
  • 389
  • 494