1

I want to get the last selected <option> in a <select multiple> in javascript not jquery!

The last selected option means the last option selected by the user. Not that the last option element in the select element!

I try:

<select multiple="multiple" onchange="changeEvent(this)">

function changeEvent(selectTag) {
    console.log(selectTag.value);
}

I expected to get the last <option> selected

mkhzr
  • 43
  • 4
  • Do you mean the last selected option in the list or the last option selected by the user? What do you mean by "current selected" because all the selected options are considered the current selection. – Yogi Feb 09 '23 at 12:42
  • @Yogi I mean the last selected ` – mkhzr Feb 09 '23 at 13:12
  • 1
    You can do this by using the click as that will give you the last option selected. You will need to store the values in an array so that if the user unselects an option you can rollback to the previous value. See this [working example](https://jsfiddle.net/1bcghfxy/show) on how to do it. – Yogi Feb 09 '23 at 14:35
  • 1
    @Yogi Yes, that's exactly what I meant, I got my correct answer from you. – mkhzr Feb 09 '23 at 19:23

2 Answers2

2

The value property of the select tag only returns the value of the selected option if the multiple attribute is not set. If the multiple attribute is set, you can use the options property of the <select> element to get an array of all the options and check which ones are selected.

Here's an updated version of the function with JavaScript:

function changeEvent(selectTag) {
    let selectedOptions = [];
    for (let i = 0; i < selectTag.options.length; i++) {
        if (selectTag.options[i].selected) {
            selectedOptions.push(selectTag.options[i].value);
        }
    }
    console.log(selectedOptions);
}
<select multiple="multiple" onchange="changeEvent(this)">
  <option value="option1">Option 1</option>
  <option value="option2">Option 2</option>
  <option value="option3">Option 3</option>
  <option value="option4">Option 4</option>
  <option value="option5">Option 5</option>
</select>
Filip Huhta
  • 2,043
  • 7
  • 25
2

To get all the selected options, use selectedOptions on the selectTag.

For the 'last' option, use the default selectTag.value.

Remember that .value will only contain the last selected value, so if you'd un-select some value, the previous selected will be set as value of selectTag.value

function changeEvent(selectTag) {
    const allSelectedValues = Array.from(selectTag.selectedOptions).map(t => t.value).join(', ');
    console.log(`All selected: ${allSelectedValues}`);
    console.log(`Previous: ${selectTag.value}`);
}
<select multiple="multiple" onchange="changeEvent(this)">
  <option>foo</option>
  <option>bar</option>
  <option>foobar</option>
</select>
0stone0
  • 34,288
  • 4
  • 39
  • 64