最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Getting select option text based on value - Stack Overflow

programmeradmin3浏览0评论

I have a menu. Given a given value, I would like to return the text. For instance, 0 would return “zero”, 1 would return “one”, etc. Note that I do not care which option is currently selected nor do I want to auto-select the menu, but just want to use the select menu as a primitive database. Can this be done easily with JavaScript or jQuery without iterating over each option?

<select>
<option value="0">zero</option>
<option value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
</select>

Thanks

I have a menu. Given a given value, I would like to return the text. For instance, 0 would return “zero”, 1 would return “one”, etc. Note that I do not care which option is currently selected nor do I want to auto-select the menu, but just want to use the select menu as a primitive database. Can this be done easily with JavaScript or jQuery without iterating over each option?

<select>
<option value="0">zero</option>
<option value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
</select>

Thanks

Share Improve this question asked Apr 10, 2012 at 20:33 user1032531user1032531 26.3k75 gold badges245 silver badges416 bronze badges 2
  • Use the "selected:" selector (api.jquery./selected-selector) – ckaufman Commented Apr 10, 2012 at 20:40
  • jsfiddle/ckaufman/aDU5E – ckaufman Commented Apr 10, 2012 at 20:49
Add a ment  | 

5 Answers 5

Reset to default 6

Instead of using the select as a database (requiring an expensive operation for simple lookups), create a data set from it once, then use that...

var vals = $('select option').map(function(i, el) { return el.text; })
                             .toArray();
alert(vals[2]); // "two"

Or if the option values aren't sequential 0 based indices, then use an object...

var vals = {};

$('select option').each(function(i, el) { vals[el.value] = el.text });

alert(vals[2]); // "two"
var value = '3';
alert($('select option[value=' + value + ']').text());

Live demo.

Also you might want to give the select an id and update the selector because if you have multiple dropdown lists the selector won't work:

alert($('#id_of_the_select option[value=' + value + ']').text());

How else would you scan for a value without iterating over each option? There's no magic property that does it for you.

However, you can use this code:

(function() {
    var sels = document.getElementsByTagName('select'), l = sels.length, i,
        opts, m, j, o;
    for( i=0; i<l; i++) {
        o = {};
        opts = sels[i].options;
        m = opts.length;
        for( j=0; j<m; j++) o[opts[j].value] = opts[j].text;
        sels[i].map = o;
    }
})();

Put that just before </body>, and now you can find the map of any <select> on your page:

var sel = document.getElementById('mySelect');
alert(sel['0']);

Use the attribute-equals selector:

var valToSearchFor = 0;
    textFromOption = $('select option[value="' + valToSearchFor + '"]').text();

This will still iterate over every option to test for the presence of the value you're looking for, but it will do so 'behind the scenes' so that you don't have to.

There's the possibility of using querySelectorAll() (albeit with more or less the same notation as the above jQuery):

var valToSearchFor = 0;
    textFromOption = document.querySelectorAll('option[value="' + valToSearchFor + '"]').innerHTML;

This, of course, requires that the browser implements querySelectorAll(), and not all do (IE particularly).

References:

  • attribute-equals [attribute="value"] selector.
  • document.querySelectorAll().

Use the selected: Selector. Example given right on the page.

http://api.jquery./selected-selector/

 $("select").change(function () {
      var str = "";
      $("select option:selected").each(function () {
            str += $(this).text() + " ";
          });
      $("div").text(str);
    })
    .trigger('change');

Replace the "div" with the event you are trying to trigger

http://jsfiddle/ckaufman/aDU5E/1/

发布评论

评论列表(0)

  1. 暂无评论