-1

Suppose the below HTML dropdown:

I am looking for the javascript to get desired option text base on its value.

Like if asked for what is the text on value="2"? Answer: "Value 2"

I tried the below jquery code:

$(document).ready(function() {
  var value = "2";
  // I am getting an error as a output on console
  var textValue = $("#test").options[value.selectedIndex].text;
  console.log(textValue);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="test" name="test">
  <option value="0">Select Value...</option>
  <option value="1">Value 1</option>
  <option value="2">Value 2</option>
  <option value="3">Value 3</option>
</select>
  • 1
    _"I am getting "0" as a output on console"_ - How? `$("#test")` returns a jQuery object. These have no `.options` property, hence `.options[value.selectedIndex]` will throw an error. – Andreas Apr 23 '21 at 12:09
  • 1
    [How much research effort is expected of Stack Overflow users?](https://meta.stackoverflow.com/questions/261592/how-much-research-effort-is-expected-of-stack-overflow-users) – Andreas Apr 23 '21 at 12:12
  • Sorry, got the question wrong and therefor the wrong dupes. Now its the correct one. – Andreas Apr 23 '21 at 12:18

1 Answers1

2

This should work for you:

$(document).ready(function () {
                var value = "2";
                // I am getting "0" as a output on console
                var textValue = $("#test>option[value=" + value + "]").html();
                console.log(textValue);
            });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="test" name="test">
            <option value="0">Select Value...</option>
            <option value="1">Value 1</option>
            <option value="2">Value 2</option>
            <option value="3">Value 3</option>
        </select>
nilsf
  • 118
  • 1
  • 10