Gandalf
February 19, 2019, 1:06pm
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.
mawburn
February 19, 2019, 2:16pm
2
clcb.querySelectorAll('option').forEach(o => {
if (o.value === '2') {
o.selected = 'selected'
}
})
1 Like
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
mawburn
February 19, 2019, 11:55pm
4
filter/map/reduce return things, there’s no need to handle returns here.