2016-07-14 3 views
1

選択肢変更イベントでは、選択値を得るために$("select option:selected")のような不器用なコードを書くのではなく、選択した値を得るためにthis.target.targetを取得できないのはなぜですか?なぜオプションの変更イベントを選択すると、thisとevent.targetを選択した値を取得できないのですか?

+0

'this.value'または' event.target.value'が機能するはずです。 – Barmar

+0

うまく動作します:https://jsfiddle.net/barmar/a6gkggwx/1/ – Barmar

+0

'change'イベントを' option'ではなく 'select'にバインドしてください。 – Barmar

答えて

2

$("select").on('change', function(){ 
 
    console.log($(this).val()); 
 
    console.log($(this).find('option:selected').attr('data-attribute')); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<select> 
 
    <option data-attribute="a">1</option> 
 
    <option data-attribute="b">2</option> 
 
    <option data-attribute="c">3</option> 
 
    <option data-attribute="d">4</option> 
 
</select>

+0

これは非常に近い答えであると思われる – Prageeth

+0

しかし、事は私が選択したDOMのデータ属性を読み取るためにDOMを取得する必要があります – Prageeth

+0

これはあなたが必要なものですか?私は私の答えを編集しました。 –

0

それが存在している...

var selectElem = document.getElementById('select'); 
 

 
selectElem.addEventListener('change', onSelect_change); 
 

 
function onSelect_change(domEvent){ 
 
\t // get the selected value : 
 
\t var selectedValue = domEvent.target[domEvent.target.selectedIndex].value; 
 
    // you can also do it using domEvent.target.value but the other solution allows you to get every option's property you want 
 
\t 
 
\t console.log("Selected: " + selectedValue); 
 
}
<select id="select" name="select"> 
 
    <option value="value1">Value 1</option> 
 
    <option value="value2" selected>Value 2</option> 
 
    <option value="value3">Value 3</option> 
 
</select>

はそれが役に立てば幸い例えば、このコードを見てみましょう;)

PS:あなたがもっと欲しい場合はhttp://www.w3schools.com/jsref/prop_select_selectedindex.aspの表情を持っています例

1

選択した値は取得できませんが、もちろん要素とevent.taを取得できますrget。

<select onchange="mySelectOnchange(this, event)"></select> 

function mySelectOnchange(elm, e) { 
    // ** 
} 
1

そのドロップダウンメニューからオプションを選択する主な目的だから自動的<select>素子自体に選択されたオプションから転送された唯一のプロパティは、値であります。 <select>が独自の属性を持つことが可能であるため、data-*などの他の属性は自動的にコピーされません。

<select id="x" data-name="select"> 
    <option value="1" data-name="option1">1</option> 
    <option value="2" data-name="option2">2</option> 
</select> 

$("#x").data("name")ではなく<select>の名前の選択したオプションの名前を返すことは意味がありません。

関連する問題