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

Time:05-26

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'  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

CodePudding user response:

<select id='type' name='type'  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>
  • Related