Mrweiner
Mrweiner

Reputation: 521

element.prevUntil("option:contains()") not returning expected result

Let's say that I have no control over the format of the HTML, which is:

<select id="foods">
  <option value='0'>Some Vegetables</option>
  <option value='1'>-Carrot</option>
  <option value='2'>Some Fruits</option>
  <option value='3'>-Apple</option>
  <option value='4'>-Orange</option>
  <option value='5' selected='selected'>-Strawberry</option>
<select>

I am trying to get the "parent" option of Strawberry, which would be 'Some Fruits'. I'd assume that I could do that with:

var strawberry = $('#foods).find(':selected')
// This gives me strawberry.text() = '-Strawberry', as expected
var parentVal = strawberry.prevUntil("option:not(:contains('-'))").val()

However, this returns parentVal = 4, corresponding with -Orange.

var parentVal = strawberry.prevUntil("option:contains('-')").val()

...gives me parentText = undefined

var parentVal = strawberry.prevUntil("option:contains('Fruits')").val()

...gives me parentVal = 4, corresponding with -Orange.

var parentVal = strawberry.prevUntil("option:contains('Fruits'))").prev().val()

...gives me parentVal = 3, corresponding with -Apple.

What's going on? Obviously I'm misunderstanding how .prevUntil() works, or at least how it works in the context of <option> elements. Any input on what's going on and how I can return 'Some Fruits' when any of the fruits are selected?

Upvotes: 1

Views: 24

Answers (1)

Use .prevAll() insted of .prevUntil()

var parentVal = strawberry.prevAll("option:contains('Fruits')").val()

Demo

var strawberry = $('#foods').find(':selected')
var parentVal = strawberry.prevAll("option:contains('Fruits')").val()

console.log(parentVal)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="foods">
  <option value='0'>Some Vegetables</option>
  <option value='1'>-Carrot</option>
  <option value='2'>Some Fruits</option>
  <option value='3'>-Apple</option>
  <option value='4'>-Orange</option>
  <option value='5' selected='selected'>-Strawberry</option>
<select>

Upvotes: 1

Related Questions