Html select list - get text value by passing a variable?

I have a select list that displays list languages.

<select name="language_code" id="id_language_code">
    <option value="ar">Arabic - العربية</option>
    <option value="bg">Bulgarian - </option>
    <option value="zh-CN">Chinese (Simplified) - 中文 (简体)‎</option>
    <option value="en" selected="selected">English (US)</option>
    <option value="fr-CA">French (Canada) - français (Canada)‎</option>
</select>

I can get the text value of the selected value using the following code [returns English (US) from the above selection list]:

$('#id_language_code option:selected').text()

How to get a text value if I pass the value of the 'bg' parameter as a variable when the selected value is still in English (USA)?

This means that the return value will be "Bulgarian - Bulgarian" when the selected value is still "English (USA)".

I searched Google and SO for an answer, but could not find it, so I think it is not as easy as I thought it was!

+4
3

, CSS value:

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

var bgText = getOptionTextByValue('bg');

http://plnkr.co/edit/SQ48SmoQkSUgDpQ5BNAx?p=preview

+4

, (html/dom), , → , → .

, , :

var languages = [
    {short: "ar", text: "Arabic - العربية"},
    {short: "bg", text: "Bulgarian - "},
    {short: "en", value: "English (US)"}
];

, , " " bg "?"

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

DOM:

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';
+1

, , , <select>, . JavaScript (aka. No jQuery, , - ):

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.";
}

<select> , :

getSelectLabel("id_language_code", "bg");

JSFiddle, . ! , .

0

All Articles