2017-02-16 13 views
0

複数のオプションを持つ要素ボックスを選択しました。複数選択後の複数選択要素

A 
B 
C 
D 

また、複数のオプションを同時に選択できます(Ctrl +クリック)。これには複数の属性もあります。現在、私は、選択した要素のidを返し

var example= document.getElementById('selectedboxid'); 

使用してい (私は必要なものは何かを!)。 問題私が直面するのは、ユーザーが複数の要素を選択したい場合、getElementByIdは同じID(最初にクリックされたユーザー)を返します。私は、クリックごとに、クリックされた要素IDを新たに返す必要があります(複数の要素を同時に選択する)。これはどのように達成できますか?

コードは次のようになります。

var example = document.getElementById('select_example'); 

    select_example.addEventListener('change', function() { 
     var elementID = select_example.value;  // Element ID stays the same... 
      ... 
     } 
    }); 
+0

@EvanKnowlesはあなた言及したトピックに回答 'すべて' の値(選択)を取得しています。私はちょうどクリックした最後のものが必要です。それを行うための簡単な/エレガントな方法はありますか?私もプレーンJavaScriptを使用しています。 – Poo123

答えて

0

これが最後の1をクリック取得しても完全なリストをつかむために働く必要があります。

var sel = document.getElementById('sel'); 
 

 
// GEt all selected 
 
sel.addEventListener('change',function() { 
 
    
 
    console.log(this.selectedOptions); 
 
    
 
}); 
 

 

 
// Get the one clicked 
 
sel.addEventListener('click', function(evt) { 
 
    console.log(evt.target); 
 
});
select { 
 
    width: 200px; 
 
    height: 200px; 
 
    }
<select id="sel" multiple> 
 
    <option value="1">1</option> 
 
    <option value="2">2</option> 
 
    <option value="3">3</option> 
 
    <option value="4">4</option> 
 
</select>

+0

まさに私が探していたもの!ありがとうございました。 – Poo123

+0

うれしい私は助けることができた。 – creativekinetix

0

Youtのは、このようにそれを行うことができます。

var selectedOptions = document.querySelectorAll('#select_example option:checked') 

これは、選択したすべてのオプションの要素のNodeListを返します

var selectedValues = Array.prototype.map.call(selectedOptions, function(el){return el.value}) 

これは、の配列をマッピングします選択されたオプション要素を選択された値の配列に変換する。

0

selectedOptionsプロパティを使用します。例:

<select id="myselect" multiple="multiple"> 
<option value="0">0-0-0-0-0-0</option> 
<option value="1">1-1-1-1-1-1</option> 
<option value="2">2-2-2-2-2-2</option> 
<option value="3">3-3-3-3-3-3</option> 
<option value="4">4-4-4-4-4-4</option> 
</select> 

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

function processChange(event) { 
    var selectElement = event.target; 
    console.log(selectElement.selectedOptions); 
} 

select.addEventListener('change', processChange); 

の作業例:https://jsfiddle.net/a8nbj7rw/