変更のイベントをキャッチする方法< select> jQueryで?

StackOverflow https://stackoverflow.com/questions/1403297

  •  05-07-2019
  •  | 
  •  

質問

<select id="target">
<option value="1">item1</option>
<option value="2">item2</option>
<option value="3">item3</option>
</select>

言う、選択した値に応じていくつかの処理を行いたい。

役に立ちましたか?

解決

$('#target').change( function() {
   $(this).find(":selected").each(function () {
            console.log( $(this).val() );
    });
 });

他のヒント

$("#target").change( function() {
    alert($("#target option:selected").val());
});

ユーザーがオプションを変更せず、単にドロップダウンをクリックして同じアイテムを選択する場合にも、これを考慮する必要があります。

$("#target option").click( function() {
     alert($("#target option:selected").val());
});
$("#target").change( function() {
  var selectedOption = $("#target option:selected");
  var selectedValue = selectedOption.val();  // gets the selected value
  var selectedText = selectedOption.text();  // gets the selected text
});

受け入れられた答えは大丈夫ですが、キー押下(矢印キーまたは英数字キー)によって行われた変更をキャッチしません。

これはより良いアプローチです:

$('#target').bind("change keyup",function() {
   $(this).find(":selected").each(function () {
     // do something amazing here
   });
});

次の方法で、選択した値とテキストを取得できます。

$("#target").change(function() {
  var selectedValue = $(this).val(),
      selectedText = $('option:selected', this).text();
  // ...
});

矢印関数を使用すると、次のようになります。

$('#target').change((e) =>{
        console.log(e.currentTarget.value);
        console.log(e.currentTarget.textContent);
 });

this event.currentTarget に置き換えます。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top