Machtyn
Machtyn

Reputation: 3272

how to multi-select by label using playwright's locator.selectOption

I've got a multiselect <select> element where I want to select more than one item via the label. I know it is possible to multiselect by value.

<select name="colors" id="colors" multiple="multiple" size=5>
  <option value="R">Red</option>
  <option value="O">Orange</option>
  <option value="Y">Yellow</option>
  <option value="G">Green</option>
  <option value="B">Blue</option>
  <option value="P">Purple</option>
</select>

Given the above example, I know I could do page.selectOption('#colors', ['R', 'G', 'B']); and be able to have Red, Green, and Blue selected. But if I don't know the value, but only the label text, can I do the same thing? Maybe page.selectOption('#colors', {label: ['Red', 'Green', 'Blue']});?

Upvotes: 0

Views: 2380

Answers (1)

Machtyn
Machtyn

Reputation: 3272

I didn't see this question asked this way specifically. But I did find my answer, if anyone else should look for this.

Essentially, you put your labels into an array. Not your text into an array associated with label.

page.selectOption('#colors', [{label: 'Red'}, {label: 'Green'}, {label: 'Blue'}]

And, suppose all you have is the array of values to be selected const colors = ["Red", "Green", "Blue"];

You can do the following:

page.selectOption('#colors', colors.map(function(color, i) { return { label: color }; });

Upvotes: 1

Related Questions