How to print the selected value of only one option from html drop down list menu

Issue

Hello i have this drop down list menu and i want to make a script that when i select only the last option the labels change in html. This is my code i have done until now:

<select id='type' name='type' class="form-control" onchange="loadText(this)">
  <option value="S">S</option>
  <option value="B">B</option>

  <option value="F">F</option>

</select>
<script>
  function loadText(select) {
    alert(select.options[select.valueOf(2)].text);
  }
</script>

I tried to get the value of the selected option but it wont work, before i had it

select.selectedIndex

but i want this function to work only for the last value not for all 3

Solution

<select id='type' name='type' class="form-control" onchange="loadText(this)">
    <option value="S">S</option>
    <option value="B">B</option>
    <option value="F">F</option>
</select>

<script>
    function loadText(select) {
        var select = document.getElementById('type');

        var lastValue = select.options[select.options.length - 1].value;
        var selectedValue = select.options[select.selectedIndex].text;

        if (lastValue === selectedValue) {
            alert(selectedValue);
        }
    }
</script>

Answered By – adrianMoskal

Answer Checked By – Marilyn (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.