html select list - get text value by passing in a variable?

孤街醉人 提交于 2019-12-03 17:00:59

Here is an example of how you can use CSS selectors to query the value attribute:

function getOptionTextByValue(value) {
  return $('#id_language_code option[value=' + value +  ']').text();
}

var bgText = getOptionTextByValue('bg');

Here is a working example http://plnkr.co/edit/SQ48SmoQkSUgDpQ5BNAx?p=preview

You have some data, and you have the view of this data (html/dom), but it's best if you go data -> view, rather than view -> data.

For example, say you have this array:

var languages = [
    {short: "ar", text: "Arabic - العربية"},
    {short: "bg", text: "Bulgarian - Български"},
    {short: "en", value: "English (US)"}
];

Now you can look things up, for example, "what is the text for the abbreviation 'bg'?"

languages.filter(function(x){ return x.short === 'bg' })[0].text;

Or create DOM nodes from it:

function option(x){
    var el = document.createElement('option');
    el.value = x.short; el.textContent = el.text;
    return el;
}

function select(options){
    var el = document.createElement('select');
    options.forEach(function(x){ el.appendChild(x); });
    return el;
}

var element = select(languages.map(option));
element.id = 'id_language_code';

Hmm, if I understand correctly, you want to retrieve the label associated with a given value of one of the options of the <select> element, which will not necessarily be the currently selected option. Using pure JavaScript approach (aka. No jQuery, since there's already a nice one provided by someone else):

function getOptionLabel(selectId, optionValue){
    // Get select element and all options
    var sel = document.getElementById(selectId);
    var selOpts = sel.options;

    // Cycle through each option to compare its value to the desired one
    for(var i = 0; i < selOpts.length; i++){
        if (selOpts[i].value == optionValue){
            return selOpts[i].label;
        }
    }

    // Default return value
    return "Option not found.";
}

To get the Bulgarian option from a <select> of the given id, you could call it like so:

getSelectLabel("id_language_code", "bg");

Here's a JSFiddle to demonstrate. Hope this helps! Let me know if you have any questions.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!