76

I want to set a dropdown box to whatever has been passed through a querystring using jquery.

How do I add the selected attribute to an option such that the "TEXT" value is equal to a certain param from the query string?

 $(document).ready(function() {
        var cat = $.jqURL.get('category');
        if (cat != null) {
            cat = $.URLDecode(cat);
            var $dd = $('#cbCategory');
            var $options = $('option', $dd);
            $options.each(function() {
                if ($(this).text() == cat)
                    $(this).select(); // This is where my problem is
            });
        };
    });
Mark Amery
  • 143,130
  • 81
  • 406
  • 459
OneSmartGuy
  • 2,849
  • 4
  • 25
  • 24
  • possible duplicate of [jQuery - setting the selected value of a select control via its text description](http://stackoverflow.com/questions/496052/jquery-setting-the-selected-value-of-a-select-control-via-its-text-description) – Mark Amery Jul 01 '13 at 21:44

3 Answers3

173

Replace this:

var cat = $.jqURL.get('category');
var $dd = $('#cbCategory');
var $options = $('option', $dd);
$options.each(function() {
if ($(this).text() == cat)
    $(this).select(); // This is where my problem is
});

With this:

$('#cbCategory').val(cat);

Calling val() on a select list will automatically select the option with that value, if any.

umar_
  • 491
  • 5
  • 17
Paolo Bergantino
  • 480,997
  • 81
  • 517
  • 436
  • 2
    am not able to do multiple options select with this approach ? – Akhi Oct 19 '12 at 21:14
  • 2
    This method does not trigger events on $('#cbCategory') element. – Jānis Gruzis Oct 22 '12 at 10:48
  • 15
    This answer is out of date. As of jQuery 1.4, `.val` will only select options by their text content if they do not have a `value` attribute. Thus in the case where the option elements have value attributes and they do not match their text content, the answer provided here will not work. – Mark Amery Apr 02 '13 at 11:26
34

I know this question is too old, but still, I think this approach would be cleaner:

cat = $.URLDecode(cat);
$('#cbCategory option:contains("' + cat + '")').prop('selected', true);

In this case you wont need to go over the entire options with each(). Although by that time prop() didn't exist so for older versions of jQuery use attr().


UPDATE

You have to be certain when using contains because you can find multiple options, in case of the string inside cat matches a substring of a different option than the one you intend to match.

Then you should use:

cat = $.URLDecode(cat);
$('#cbCategory option').filter(function(index) { 
    return $(this).text() === cat; 
}).prop('selected', true);
Guilherme David da Costa
  • 2,318
  • 4
  • 32
  • 46
22

If your <option> elements don't have value attributes, then you can just use .val:

$selectElement.val("text_you're_looking_for")

However, if your <option> elements have value attributes, or might do in future, then this won't work, because whenever possible .val will select an option by its value attribute instead of by its text content. There's no built-in jQuery method that will select an option by its text content if the options have value attributes, so we'll have to add one ourselves with a simple plugin:

/*
  Source: https://stackoverflow.com/a/16887276/1709587

  Usage instructions:

  Call

      jQuery('#mySelectElement').selectOptionWithText('target_text');

  to select the <option> element from within #mySelectElement whose text content
  is 'target_text' (or do nothing if no such <option> element exists).
*/
jQuery.fn.selectOptionWithText = function selectOptionWithText(targetText) {
    return this.each(function () {
        var $selectElement, $options, $targetOption;

        $selectElement = jQuery(this);
        $options = $selectElement.find('option');
        $targetOption = $options.filter(
            function () {return jQuery(this).text() == targetText}
        );

        // We use `.prop` if it's available (which it should be for any jQuery
        // versions above and including 1.6), and fall back on `.attr` (which
        // was used for changing DOM properties in pre-1.6) otherwise.
        if ($targetOption.prop) {
            $targetOption.prop('selected', true);
        } 
        else {
            $targetOption.attr('selected', 'true');
        }
    });
}

Just include this plugin somewhere after you add jQuery onto the page, and then do

jQuery('#someSelectElement').selectOptionWithText('Some Target Text');

to select options.

The plugin method uses filter to pick out only the option matching the targetText, and selects it using either .attr or .prop, depending upon jQuery version (see .prop() vs .attr() for explanation).

Here's a JSFiddle you can use to play with all three answers given to this question, which demonstrates that this one is the only one to reliably work: http://jsfiddle.net/3cLm5/1/

Community
  • 1
  • 1
Mark Amery
  • 143,130
  • 81
  • 406
  • 459