変更時に選択から選択した値/テキストを取得


96
<select onchange="test()" id="select_id">
    <option value="0">-Select-</option>
    <option value="1">Communication</option>
</select>

javascriptで選択したオプションの値を取得する必要があります。選択した値またはテキストを取得する方法を知っている人はいますか。そのための関数の記述方法を教えてください。選択するonchange()関数を割り当てたので、その後はどうすればよいですか?



1
選択されvalueoptionものだけが必要な場合は<select onchange="window.alert(this.value);">...... options ... </select>...それだけで、それ以上は取得できません。
S0AndS0

回答:


114

これにはJavaScriptまたはjQueryのいずれかを使用してください。

JavaScriptの使用

<script>
function val() {
    d = document.getElementById("select_id").value;
    alert(d);
}
</script>

<select onchange="val()" id="select_id">

jQueryの使用

$('#select_id').change(function(){
    alert($(this).val());
})

.value()は最新のブラウザでは機能しますが、実際には古いブラウザでは機能しません。bytes.com/topic/javascript/answers/…を
Benissimo

2
@PlayHardGoProそれが選択された値です。テキスト(例:-Select-またはCommunication)が必要な場合は、text:select.textまたはjQueryを使用しますselect.text()
ricksmt 2013

jqueryの最後にセミコロンがありません... :)
lindhe 2015年

jQueryを使用$('#select_id option:selected').text()します。これにより、選択したオプション、選択または通信
Paulo Borralho Martins 2016

1
バニラジャバスクリプトアプローチ: document.getElementById("select_id").onchange = (evt) => { console.log(evt.srcElement.value); }
スペンサー

44

これをグーグルで検索していて、イベントリスナーを属性にしたくない場合は、次を使用します。

document.getElementById('my-select').addEventListener('change', function() {
  console.log('You selected: ', this.value);
});
<select id="my-select">
  <option value="1">One</option>
  <option value="2">Two</option>
  <option value="3">Three</option>
</select>


30

function test(a) {
    var x = (a.value || a.options[a.selectedIndex].value);  //crossbrowser solution =)
    alert(x);
}
<select onchange="test(this)" id="select_id">
    <option value="0">-Select-</option>
    <option value="1">Communication</option>
    <option value="2">Communication</option>
    <option value="3">Communication</option>
</select>


何のa.valueために?実際にそのようなブラウザをサポートしているブラウザはありますか?ただ使うことはできませんa.options[a.selectedIndex].value
匿名

@Anonymous <to get the subj =)
el Dude

27

onchange関数は必要ありません。1行で値を取得できます。

document.getElementById("select_id").options[document.getElementById("select_id").selectedIndex].value;

または、読みやすくするために分割します。

var select_id = document.getElementById("select_id");

select_id.options[select_id.selectedIndex].value;

20

うわー、答えの中で本当に再利用可能な解決策はまだありません..つまり、標準のイベントハンドラーは event引数 IDを使用する必要はまったくありません。

function handleSelectChange(event) {

    // if you want to support some really old IEs, add
    // event = event || window.event;

    var selectElement = event.target;

    var value = selectElement.value;
    // to support really old browsers, you may use
    // selectElement.value || selectElement.options[selectElement.selectedIndex].value;
    // like el Dude has suggested

    // do whatever you want with value
}

このハンドラーは、それぞれ–インラインjsで使用できます。

<select onchange="handleSelectChange(event)">
    <option value="1">one</option>
    <option value="2">two</option>
</select>

jQuery:

jQuery('#select_id').on('change',handleSelectChange);

またはバニラJSハンドラー設定:

var selector = document.getElementById("select_id");
selector.onchange = handleSelectChange;
// or
selector.addEventListener('change', handleSelectChange);

そして、selectあなたが持っている要素ごとにこれを書き直す必要はありません。

スニペットの例:

function handleSelectChange(event) {

    var selectElement = event.target;
    var value = selectElement.value;
    alert(value);
}
<select onchange="handleSelectChange(event)">
    <option value="1">one</option>
    <option value="2">two</option>
</select>


2
素晴らしい解決策、受け入れられるべきです。DOMドキュメントを参照せずに純粋なイベント要素を使用することは、React、Vue、または単なるHTMLフォームなどの多くの環境で機能する最も柔軟な方法です。
vanDavv 2018年

8
let dropdown = document.querySelector('select');
if (dropdown) dropdown.addEventListener('change', function(event) {
    console.log(event.target.value);
});

このアプローチは、矢印関数を使用している場合に役立ちます。
フランチー

どの矢印関数もfunction(){}に置き換えることができます。同じことです
Russell Strauss

それは同じではありません。this矢印関数では、字句環境からコンテキストを取得しますが、通常の関数には独自のコンテキストがあります。これを
フランチー

6

使用する

document.getElementById("select_id").selectedIndex

または値を取得するには:

document.getElementById("select_id").value

値を取得するこの方法は古いブラウザでは機能しません。代わりにDannyのソリューションを使用してください
wlf 2013

5
<script>
function test(a) {
    var x = a.selectedIndex;
    alert(x);
}
</script>
<select onchange="test(this)" id="select_id">
    <option value="0">-Select-</option>
    <option value="1">Communication</option>
    <option value="2">Communication</option>
    <option value="3">Communication</option>
</select>

アラートでは、選択されたインデックスのINT値が表示され、選択が配列として扱われ、値が取得されます。


5

HTML:

<select onchange="cityChanged(this.value)">
      <option value="CHICAGO">Chicago</option>
      <option value="NEWYORK">New York</option>
</select>

JS:

function cityChanged(city) {
    alert(city);
}

4

私は誰もがについて投稿したことだろうvaluetextオプションから取得する<option>と、誰も提案しませんlabel

だから私labelも提案しています、すべてのブラウザでサポートされています

取得するvalue(他の人が提案したのと同じ)

function test(a) {
var x = a.options[a.selectedIndex].value;
alert(x);
}

取得するにはoption text(つまり、コミュニケーションまたは-選択-)

function test(a) {
var x = a.options[a.selectedIndex].text;
alert(x);
}

または (新しい提案)

function test(a) {
var x = a.options[a.selectedIndex].label;
alert(x);
}

HTML

<select onchange="test(this)" id="select_id">
    <option value="0">-Select-</option>
    <option value="1">Communication</option>
    <option value="2" label=‘newText’>Communication</option>
</select>

注:上記のHTMLのoption値2では、CommunicationではなくnewTextlabelが返されます

また

注:Firefoxでlabelプロパティを設定することはできません(returnのみ)。


3

これは古い質問ですが、DOMを再度検索する代わりに、イベントオブジェクトを使用して情報を取得することを人々が提案しなかった理由はわかりません。

関数onChangeでイベントオブジェクトを確認するだけです。以下の例を参照してください。

function test() { console.log(event.srcElement.value); }

http://jsfiddle.net/Corsico/3yvh9wc6/5/

これが7年前のデフォルトの動作ではなかった場合、今日これを調べている人々に役立つかもしれません


2

function test(){
  var sel1 = document.getElementById("select_id");
  var strUser1 = sel1.options[sel1.selectedIndex].value;
  console.log(strUser1);
  alert(strUser1);
  // Inorder to get the Test as value i.e "Communication"
  var sel2 = document.getElementById("select_id");
  var strUser2 = sel2.options[sel2.selectedIndex].text;
  console.log(strUser2);
  alert(strUser2);
}
<select onchange="test()" id="select_id">
  <option value="0">-Select-</option>
  <option value="1">Communication</option>
</select>


0

function test(){
  var sel1 = document.getElementById("select_id");
  var strUser1 = sel1.options[sel1.selectedIndex].value;
  console.log(strUser1);
  alert(strUser1);
  // Inorder to get the Test as value i.e "Communication"
  var sel2 = document.getElementById("select_id");
  var strUser2 = sel2.options[sel2.selectedIndex].text;
  console.log(strUser2);
  alert(strUser2);
}
<select onchange="test()" id="select_id">
  <option value="0">-Select-</option>
  <option value="1">Communication</option>
</select>

var e = document.getElementById("ddlViewBy");
var strUser = e.options[e.selectedIndex].value;

-1

私自身のサンプルで説明しようとしましたが、お役に立てば幸いです。onchange = "test()"は必要ありません。ライブ結果を取得するには、コードスニペットを実行してください。

document.getElementById("cars").addEventListener("change", displayCar);

function displayCar() {
  var selected_value = document.getElementById("cars").value;
  alert(selected_value);
}
<select id="cars">
  <option value="bmw">BMW</option>
  <option value="mercedes">Mercedes</option>
  <option value="volkswagen">Volkswagen</option>
  <option value="audi">Audi</option>
</select>


オプションを選択するのは癌ではないので、変更時はクリックイベントよりもはるかに優れています。
ライリーカーニー2018年

@RileyCarneyまあ、それは、js部分の関数名の変更に応じてui部分のリファクタリングコードを変更する代わりに、よりエレガントで、クリックイベントが表示されなかったことに依存します。

onclickイベントを削除するように編集しました。あなたが車のためにそれをクリックした場合に通知を行ったクリックを行う前に、とても日陰です。edited 7 hours ago少なくとも、うまく機能しなかったコードを修正しました。
ライリーカーニー2018
弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.