I have a select list that displays a 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 am able to get the text value of the selected value using the following code [returns English (US) from the above select list]:
$('#id_language_code option:selected').text()
How can I get the text value if I pass the option value of 'bg' as a variable when the selected value is still English (US)?
This means that the value returned would be "Bulgarian - Български" when the selected value is still "English (US)".
I have searched Google and SO for an answer, but was unable to find one, so I am thinking that this is not as easy as I 1st thought it was!
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:
Now you can look things up, for example, "what is the text for the abbreviation 'bg'?"
Or create DOM nodes from it:
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):To get the Bulgarian option from a
<select>
of the given id, you could call it like so:Here's a JSFiddle to demonstrate. Hope this helps! Let me know if you have any questions.
Here is an example of how you can use CSS selectors to query the
value
attribute:Here is a working example http://plnkr.co/edit/SQ48SmoQkSUgDpQ5BNAx?p=preview