Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to get last selected option in multiple select in javascript

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

I try:

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

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

I expected to get the last <option> selected

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

For the ‘last’ one pop() the array!

function changeEvent(selectTag) {
    console.log(selectTag.selectedOptions);
}
<select multiple="multiple" onchange="changeEvent(this)">
  <option>foo</option>
  <option>bar</option>
  <option>foobar</option>
</select>
  
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading