-3

I have a question. I have a scenario where I need to get value of option tag based on option text.

<select>
  <option value="0">zero</option>
  <option value="1">one</option>
  <option value="2">two</option>
  <option value="3">three</option>
</select>

Here imagine that I want to get the value "2" based on the supplied text "two". How can we achieve that?

Zsolt Meszaros
  • 21,961
  • 19
  • 54
  • 57
user12893845
  • 176
  • 2
  • 13
  • 6
    Have you googled "how to get select value"? "How to get element by text"? What have you tried so far? – Roko C. Buljan May 21 '20 at 11:39
  • https://www.w3schools.com/JSREF/tryit.asp?filename=tryjsref_select_value – iepure May 21 '20 at 11:41
  • Does this answer your question? [jQuery - setting the selected value of a select control via its text description](https://stackoverflow.com/questions/496052/jquery-setting-the-selected-value-of-a-select-control-via-its-text-description) – freedomn-m May 21 '20 at 11:44
  • or this?: https://www.w3schools.com/jsref/prop_text_value.asp – joshii_h May 21 '20 at 12:53

1 Answers1

0

You can try something like this javascript

Say this what you provided :

<select id="test">
<option value="0">zero</option>
<option value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
</select>

var e = document.getElementById("test");
var actualValue= e.options[e.selectedIndex].value;
Harmandeep Singh Kalsi
  • 3,315
  • 2
  • 14
  • 26