[javascript] JQuery - how to select dropdown item based on value

I want set a dropdown(select) to be change based on the value of the entries.

I have

<select id="mySelect">
  <option value="ps">Please Select</option>
  <option value="ab">Fred</option>
  <option value="fg">George</option>
  <option value="ac">Dave</option>
</select>

And I know that I want to change the dropdown so that the option with the value of "fg" is selected. How can I do this with JQuery?

This question is related to javascript jquery select jquery-selectors

The answer is


$('#mySelect').val('fg');...........

 $('#mySelect').val('ab').change();

 // or

 $('#mySelect').val('ab').trigger("change");

You can simply use:

$('#select_id').val('fg')

You can use this jQuery code which I find it eaiser to use:

_x000D_
_x000D_
$('#your_id [value=3]').attr('selected', 'true');
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<select id="your_id" name="name" class="form-control input-md">_x000D_
  <option value="1">Option #1</option>_x000D_
  <option value="2">Option #2</option>_x000D_
  <option value="3">Option #3</option>_x000D_
  <option value="4">Option #4</option>_x000D_
  <option value="5">Option #5</option>_x000D_
  <option value="6">Option #6</option>_x000D_
  <option value="7">Option #7</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_


May be too late to answer, but at least some one will get help.

You can try two options:

This is the result when you want to assign based on index value, where '0' is Index.

 $('#mySelect').prop('selectedIndex', 0);

don't use 'attr' since it is deprecated with latest jquery.

When you want to select based on option value then choose this :

 $('#mySelect').val('fg');

where 'fg' is the option value


This code worked for me:

$(function() {
    $('[id=mycolors] option').filter(function() { 
        return ($(this).text() == 'Green'); //To select Green
    }).prop('selected', true);
});

With this HTML select list:

<select id="mycolors">
      <option value="1">Red</option>
      <option value="2">Green</option>
      <option value="3">Blue</option>
</select>

_x000D_
_x000D_
$('#dropdownid').val('selectedvalue');
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<select id='dropdownid'>_x000D_
    <option value=''>- Please choose -</option>_x000D_
    <option value='1'>1</option>_x000D_
    <option value='2'>2</option>_x000D_
    <option value='selectedvalue'>There we go!</option>_x000D_
    <option value='3'>3</option>_x000D_
    <option value='4'>4</option>_x000D_
    <option value='5'>5</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_


$('#yourdropddownid').val('fg');

Optionally,

$('select>option:eq(3)').attr('selected', true);

where 3 is the index of the option you want.

Live Demo


I have a different situation, where the drop down list values are already hard coded. There are only 12 districts so the jQuery Autocomplete UI control isn't populated by code.

The solution is much easier. Because I had to wade through other posts where it was assumed the control was being dynamically loaded, wasn't finding what I needed and then finally figured it out.

So where you have HTML as below, setting the selected index is set like this, note the -input part, which is in addition to the drop down id:

$('#project-locationSearch-dist-input').val('1');

                <label id="lblDistDDL" for="project-locationSearch-input-dist" title="Select a district to populate SPNs and PIDs or enter a known SPN or PID." class="control-label">District</label>
                <select id="project-locationSearch-dist" data-tabindex="1">
                    <option id="optDistrictOne" value="01">1</option>
                    <option id="optDistrictTwo" value="02">2</option>
                    <option id="optDistrictThree" value="03">3</option>
                    <option id="optDistrictFour" value="04">4</option>
                    <option id="optDistrictFive" value="05">5</option>
                    <option id="optDistrictSix" value="06">6</option>
                    <option id="optDistrictSeven" value="07">7</option>
                    <option id="optDistrictEight" value="08">8</option>
                    <option id="optDistrictNine" value="09">9</option>
                    <option id="optDistrictTen" value="10">10</option>
                    <option id="optDistrictEleven" value="11">11</option>
                    <option id="optDistrictTwelve" value="12">12</option>
                </select>

Something else figured out about the Autocomplete control is how to properly disable/empty it. We have 3 controls working together, 2 of them mutually exclusive:

//SPN
spnDDL.combobox({
    select: function (event, ui) {
        var spnVal = spnDDL.val();
        //fire search event
        $('#project-locationSearch-pid-input').val('');
        $('#project-locationSearch-pid-input').prop('disabled', true);
        pidDDL.empty(); //empty the pid list
    }
});
//get the labels so we have their tool tips to hand.
//this way we don't set id values on each label
spnDDL.siblings('label').tooltip();

//PID
pidDDL.combobox({
    select: function (event, ui) {
        var pidVal = pidDDL.val();
        //fire search event
        $('#project-locationSearch-spn-input').val('');
        $('#project-locationSearch-spn-input').prop('disabled', true);
        spnDDL.empty(); //empty the spn list
    }
});

Some of this is beyond the scope of the post and I don't know where to put it exactly. Since this is very helpful and took some time to figure out, it's being shared.

Und Also ... to enable a control like this, it's (disabled, false) and NOT (enabled, true) -- that also took a bit of time to figure out. :)

The only other thing to note, much in addition to the post, is:

    /*
Note, when working with the jQuery Autocomplete UI control,
the xxx-input control is a text input created at the time a selection
from the drop down is picked.  Thus, it's created at that point in time
and its value must be picked fresh.  Can't be put into a var and re-used
like the drop down list part of the UI control.  So you get spnDDL.empty()
where spnDDL is a var created like var spnDDL = $('#spnDDL);  But you can't
do this with the input part of the control.  Winded explanation, yes.  That's how
I have to do my notes or 6 months from now I won't know what a short hand note means
at all. :) 
*/
    //district
    $('#project-locationSearch-dist').combobox({
        select: function (event, ui) {
            //enable spn and pid drop downs
            $('#project-locationSearch-pid-input').prop('disabled', false);
            $('#project-locationSearch-spn-input').prop('disabled', false);
            //clear them of old values
            pidDDL.empty();
            spnDDL.empty();
            //get new values
            GetSPNsByDistrict(districtDDL.val());
            GetPIDsByDistrict(districtDDL.val());
        }
    });

All shared because it took too long to learn these things on the fly. Hope this is helpful.


$('select#myselect option[value="ab"]').


You can select dropdown option value by name

// deom
jQuery("#option_id").find("option:contains('Monday')").each(function()
{
 if( jQuery(this).text() == 'Monday' )
 {
  jQuery(this).attr("selected","selected");
  }

});

In your case $("#mySelect").val("fg") :)


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 jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to select

Warning: Use the 'defaultValue' or 'value' props on <select> instead of setting 'selected' on <option> SQL query to check if a name begins and ends with a vowel Angular2 *ngFor in select list, set active based on string from object SQL: Two select statements in one query How to get selected value of a dropdown menu in ReactJS DATEDIFF function in Oracle How to filter an array of objects based on values in an inner array with jq? Select unique values with 'select' function in 'dplyr' library how to set select element as readonly ('disabled' doesnt pass select value on server) Trying to use INNER JOIN and GROUP BY SQL with SUM Function, Not Working

Examples related to jquery-selectors

Why is my JQuery selector returning a n.fn.init[0], and what is it? How to use placeholder as default value in select2 framework Access the css ":after" selector with jQuery jQuery: using a variable as a selector Check if any ancestor has a class using jQuery jQuery selector first td of each row Select element by exact match of its content jQuery selector to get form by name jQuery : select all element with custom attribute Set select option 'selected', by value