How can I access the "displayed" text of the window selection option from the DOM?

Given the following HTML:

<select name="my_dropdown" id="my_dropdown">
<option value="1">displayed text 1</option>
</select>

How can I capture the string "display text 1" using Javascript / DOM?

+3
source share
6 answers
var sel = document.getElementById("my_dropdown");

//get the selected option
var selectedText = sel.options[sel.selectedIndex].text;

//or get the first option
var optionText = sel.options[0].text;

//or get the option with value="1"
for(var i=0; i<sel.options.length; i++){
    if(sel.options[i].value == "1"){
        var valueIsOneText = sel.options[i].text;
    }
}
+10
source
var mySelect = document.forms["my_form"].my_dropdown;
// or if you select has a id
var mySelect = document.getElementById("my_dropdown");
var text = mySelect.options[mySelect.selectedIndex].text;
+4
source

, :

var select = document.getElementById('my_dropdown');
for(var i = 0; i < select.options.length; i++) {
    if(select.options[i].selected) {
        break;
    }
}
var selectText = select.options[i].text;

:

var selectText = $$('#my_dropdown option[selected]')[0].text;

Edit: jQuery ( , CSS jQuery Prototype):

var selectText = $('#my_dropdown option[selected]').get(0).text;
+2

node node. :

myOptionNode.childNodes[0];

, , node ( ).

: , , :

myOptionNode.text;
+1

, , id/class jQuery, - . . , , , :

$('select#id option').each(function() {
  alert($(this).text());
});

id, "select # id" "select.class". /id, .

, .

+1

Prototype, :

$$('#my_dropdown option[value=1]').each( function(elem){
                alert(elem.text);
            });

above, using the CSS selector that says, find all the parameter <strong> tags with <strong> value = "1" that are inside the element that has ID = "my_dropdown" .

0
source

Source: https://habr.com/ru/post/1698151/


All Articles