Selecting option by text content with jQuery

后端 未结 3 1039
不思量自难忘°
不思量自难忘° 2020-12-25 09:40

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\"

3条回答
  •  轮回少年
    2020-12-25 10:07

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

提交回复
热议问题