0

I have a dropdown list in html

<select id="dropdown">
    <option value="text">Text</option>
    <option value="graphic">Graphic</option>
    <option value="formula">Formula</option>
    <option value="title">Title</option>
</select>  

I am trying to get the selected option from the menu by calling a function. I tried two options:
1.I tried using onclick -the problem with this is, my function call is triggered when I click on the dropdown button but before any option is selected.
2.so I used onchange to call my function, but when I use this,the function call is not triggered if i want to use the same option in a row, because as the name suggests, the function is called only when the option is changed.
Is there any other way how i can get the selected option?

this is my script-

...  
document.addEventListener('DOMContentLoaded',function() {   document.querySelector('select[name="zonelist"]').onclick=getSelectedTextValue;
},false);  
...  
function getSelectedTextValue(){}  
...
roadrunner009
  • 29
  • 1
  • 13
  • You can also handler the `onblur` event – Ricardo Pontual Feb 05 '18 at 09:39
  • Possible duplicate of [Get selected value in dropdown list using JavaScript?](https://stackoverflow.com/questions/1085801/get-selected-value-in-dropdown-list-using-javascript) – Overflowrun Feb 05 '18 at 09:41
  • What are you doing with the selected option that would require the function be called if the same option remains selected? If it was called on the previous interaction, and there's no change, I don't understand why the function should be called, or do you simply want the function called on page-load, to show the default option? – David Thomas Feb 05 '18 at 11:29

1 Answers1

0

Add a flag to it, and use click event.

It may not work if you click outside <select>, but you can do a treatment for such cases.

var open = false;

document.getElementById('dropdown').addEventListener('click', function(e){
  open = !open;
  if(!open){
    console.log(this.options[this.selectedIndex].text)
  }
});

//check if click outside 
window.addEventListener('click', function(e){   
  if (!document.getElementById('dropdown').contains(e.target)){
    open = false;
  }
});
<select id="dropdown">
    <option value="text">Text</option>
    <option value="graphic">Graphic</option>
    <option value="formula">Formula</option>
    <option value="title">Title</option>
</select>
KL_
  • 1,503
  • 1
  • 8
  • 13