使用jQuery通过文本内容选择选项


76

我想将一个下拉框设置为使用jquery通过查询字符串传递的任何内容。

如何将所选属性添加到选项中,以使“ TEXT”值等于查询字符串中的某个参数?

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

Answers:


173

替换为:

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

有了这个:

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

调用val()选择列表将自动选择具有该值的选项(如果有)。


2
用这种方法不能做多个选择?
Akhi 2012年

2
此方法不会在$('#cbCategory')元素上触发事件。
贾尼斯·格鲁吉斯

15
这个答案已经过时了。从jQuery 1.4开始,.val如果没有value属性,则仅按文本内容选择选项。因此,在选项元素具有值属性且与文本内容不匹配的情况下,此处提供的答案将无效。
Mark Amery 2013年

34

我知道这个问题太旧了,但是我仍然认为这种方法更干净:

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

在这种情况下,您不需要使用遍历整个选项each()。尽管那时prop()还不存在,所以对于jQuery的较早版本来说可以使用attr()


更新

使用时必须确定,contains因为如果内部字符串cat匹配的子字符串与要匹配的选项的子字符串不同,则可以找到多个选项。

然后,您应该使用:

cat = $.URLDecode(cat);
$('#cbCategory option')
    .filter(function(index) { return $(this).text() === cat; })
    .prop('selected', true);

2
感谢您分享和保持最新信息!
埃里克·赫里兹

20

如果您的<option>元素没有value属性,则可以使用.val

$selectElement.val("text_you're_looking_for")

但是,如果您的<option>元素具有值属性,或者将来可能会使用,则此方法将不起作用,因为只要有可能,.val都将根据其value属性而不是其文本内容选择一个选项。如果选项具有value属性,则没有内置的jQuery方法会根据其文本内容选择一个选项,因此我们必须使用一个简单的插件自己添加一个:

/*
  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');
        }
    });
}

在将jQuery添加到页面上之后,只需将该插件包括在某处,然后执行

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

选择选项。

plugin方法用于filter仅选择option匹配的targetText,并根据jQuery版本使用.attr或选择它有关说明,.prop请参见.prop()与.attr())。

这是一个JSFiddle,可用于解决该问题的所有三个答案,这表明该答案是唯一可靠运行的答案:http : //jsfiddle.net/3cLm5/1/

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.