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>
CodePudding user response:
You can extend your filter()
to also check the value
:
Pure JS example, since you might not need jquery:
function getValue(myText = "Dog") {
const options = [ ...document.querySelectorAll("#animals option") ];
return options.filter((e) => {
return e.value !== '0' && e.innerHTML === myText;
});
}
const res = getValue();
console.log(res);
<select id = "animals">
<option value = '0'>Dog<option>
<option value = '1'>Dog<option>
<option value = '2'>Cat<option>
</select>
CodePudding user response:
I'd stick with jQuery and use its additional :contains()
selector to find the text match, along with :not()
to limit the value
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.
function getValue() {
var myText = "Dog"
return $("#animals option:contains('" myText "'):not([value='0'])").val();
}
console.log(getValue());
<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>