Setting an option to selected depending on option value

#1

I want to mark an option as selected if it has a particular value. I have got as far as

const clcb = document.getElementById("cashbook");
clcb.getElementsByTagName("option")[2].selected = "selected";

which sets the 2nd option to selected, but what I want is to set the option whose value is 2 to selected.

#2
clcb.querySelectorAll('option').forEach(o => {
  if (o.value === '2') {
    o.selected = 'selected'
  }
})
1 Like
#3

I was wondering if there’s a better way to do this using the filter/map/reduce methods.
The only trouble is what to do if no option is found, and that’s where map becomes useful.

Array.from(clcb.querySelectorAll("option"))
    .filter((o) => o.value === "2")
    .map((o) => o.selected = "selected");
2 Likes
#4

filter/map/reduce return things, there’s no need to handle returns here.

#5

Is this still working?

#6

Yes it is.

closed #7