0

I am working in a legacy application where I am in the obligation of getting the value of an option by the option text instead of the other way like usual.

Here is a non working example that I need help with

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
</head>
<body>
<select id="myselect" name="myselect">
    <option value="0">Zero</option>
    <option value="1">One</option>
    <option value="2">Two</option>
    <option value="3">Three</option>
</select>
<script>
$(document).ready(function(){
    var optionText = 'Two';
    console.log($('#myselect option[option="' + optionText + '"]').attr("value"));
});
</script>
</body>
</html>

Thanks

Karim Mtl
  • 1,223
  • 3
  • 11
  • 39
  • – Sanjay Kumar Jun 01 '18 at 19:11

2 Answers2

0

Give this a shot

$('#myselect').find('option[text="' + optionText + '"]').val();
Mike
  • 1
  • This is what the duplicate post says... Rather than duplicating answers, vote for the duplicate post. – Taplar Jun 01 '18 at 18:14
0

It seems that it depends on the version. Here is what worked for me:

$('#myselect option').filter(function () { return $(this).html() == "Two"; }).val()

Thanks

Karim Mtl
  • 1,223
  • 3
  • 11
  • 39