Given the following HTML:
<select name="my_dropdown" id="my_dropdown">
<option value="1">displayed text 1</option>
</select>
How do I grab the string "displayed text 1" using Javascript/the DOM?
Given the following HTML:
<select name="my_dropdown" id="my_dropdown">
<option value="1">displayed text 1</option>
</select>
How do I grab the string "displayed text 1" using Javascript/the 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;
編集:完全を期すために jQuery (jQuery の CSS セレクターのサポートがプロトタイプのものとほぼ同等であると仮定):
var selectText = $('#my_dropdown option[selected]').get(0).text;
The displayed text is a child node of the option node. You can use:
myOptionNode.childNodes[0];
to access it, assuming the text node is the only thing inside the option (and not other tags).
EDIT: Oh yeah, as others mentioned, I completely forgot about:
myOptionNode.text;
id / class を持つようにコードを少し変更し、jQuery を使用していると仮定すると、次のようなものになる可能性があります。オプションのテキストを含む各オプションのアラートがポップアップ表示されます。すべてのテキストに対してアラートを出す必要はないかもしれませんが、最初にテキストを取得する方法を示しています。
$('select#idオプション').each(関数() { alert($(this).text()); });
ID の代わりにクラスを使用する場合は、「select#id」を「select.class」に変更するだけです。class/id を追加したくない場合は、他の方法で選択できます。
読者の活動としてそのルートに行きたい場合は、それらの方法を考え出すことを残します.
Prototypeを使用していた場合、次のように取得できます。
$$('#my_dropdown option[value=1]').each( function(elem){
alert(elem.text);
});
上記は、id="my_dropdown"を持つ要素内にあるvalue="1"を持つすべてのオプションタグを検索するという CSS セレクターを使用しています。