Get selected value/text from Select on change

<select onchange="test()" id="select_id">
    <option value="0">-Select-</option>
    <option value="1">Communication</option>
</select>

I need to get the value of the selected option in javascript: does anyone know how to get the selected value or text, please tell how to write a function for it. I have assigned onchange() function to select so what do i do after that?


Solution 1:

Use either JavaScript or jQuery for this.

Using JavaScript

<script>
function val() {
    d = document.getElementById("select_id").value;
    alert(d);
}
</script>

<select onchange="val()" id="select_id">

Using jQuery

$('#select_id').change(function(){
    alert($(this).val());
})

Solution 2:

If you're googling this, and don't want the event listener to be an attribute, use:

document.getElementById('my-select').addEventListener('change', function() {
  console.log('You selected: ', this.value);
});
<select id="my-select">
  <option value="1">One</option>
  <option value="2">Two</option>
  <option value="3">Three</option>
</select>