So I do have this function named getValue
that retrieves option value
by using variable
that has string on it. My questions is how can I skip the option
with a value of '0'
, and just scan or find the other remaining options
. Some of you may ask, why not just change the text 'Dog'
?. In my main code var myText
is dynamic, meaning it can changed from a click, for example a table row.
code:
function getValue() {
var myText = "Dog"
$("#animals option").filter(function() {
return $(this).html() == myText;
}).val();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="animals">
<option value='0'>Dog
<option>
<option value='1'>Dog
<option>
<option value='2'>Cat
<option>
</select>
2
Answers
You can extend your
filter()
to also check thevalue
:Pure JS example, since you might not need jquery:
I’d stick with jQuery and use its additional
:contains()
selector to find the text match, along with:not()
to limit thevalue
match.Note that using
:contains()
means it will match both "Dog" and "Weiner Dog" if that option was present and would match the first one.