0

I've select element box with multiple options.

A
B
C
D

It also has "multiple" attribute, allowing user to choose multiple options at once (ctrl + click). Currently I'm using

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

which returns selected element id (what is what I need!). Problem I am facing is - if user wants to choose multiple elements, getElementById will return same id (the one, who was clicked first!). I need to return newly clicked element id on every click (choosing more than one element at once). How can this be accomplished?

Code looks like:

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

    select_example.addEventListener('change', function() {
        var elementID = select_example.value;     // Element ID stays the same...
          ...
        }
    });
Poo123
  • 49
  • 1
  • 1
  • 9
  • @EvanKnowles Answer to your mentioned topic is getting 'all' values (selected). I just need the last one clicked. Is there some easy/elegant way to do that? I am also using plain JavaScript. – Poo123 Feb 16 '17 at 07:25

3 Answers3

0

Yout can do it like this:

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

This will return NodeList of all selected option elements

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

This will map array of selected option elements to array of selected values.

Mako
  • 168
  • 1
  • 1
  • 6
0

Use selectedOptions property. Example:

<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);

Working example: https://jsfiddle.net/a8nbj7rw/

Cezary Tomczyk
  • 584
  • 1
  • 7
  • 14
0

This should work for getting the last one clicked and also grabbing the full list.

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>
creativekinetix
  • 357
  • 1
  • 7