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?
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; } }
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;
, :
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;
node node. :
myOptionNode.childNodes[0];
, , node ( ).
: , , :
myOptionNode.text;
, , id/class jQuery, - . . , , , :
$('select#id option').each(function() { alert($(this).text()); });
id, "select # id" "select.class". /id, .
, .
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" .
Source: https://habr.com/ru/post/1698151/More articles:To switch HTML people in the middle of a stream - cssКак бы вы ссылались на поисковые/метаданные? - c#Report Processor Architecture Question - c #Is it okay to use normalized tables with denormalized indexed views? - sqlCode to get * .aspx from website - asp.netHow can I use array references inside arrays in PHP? - arraysIs validation called before or after enforcement when setting DependencyProperty? - wpfLIKE in Linq to SQL - vb.netUsing Xdebug & Zend Debugger? - profilingNHibernate criteria: join two columns using an IN expression - nhibernateAll Articles