I want to loop id's of select/option elements and store the selected options text into an array which doesn't work this way:
function jsGetSelectedOptionText(optionID) {
var otext = [];
var oid;
optionID.forEach(function(id,i) {
oid = d3.select('#' + id).node();
var t = oid.options[oid.selectedIndex].text;
console.log(typeof(t), t);
otext.push(t);
});
console.log(otext);
return(otext);
}
I can see the type (string) and the text print out by console.log, but otext remains empty. What's wrong here?
You can select the option directly with a selector and read the textContent of the element.
const id = 's1';
console.log(d3.select('#' + id + ' option:checked').node().textContent);
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/7.3.0/d3.min.js" integrity="sha512-NMhzM2RHzbCRO0s5VPaRC+2bW6nmNXimzC9p5sp2x19M+zzuSJ2T50dEQ7hpHkNjnX1mt8nQg1NNthwRZgsoIg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<select class="foo" id="s1">
<option>Hello 1-1 </option>
<option selected>Hello 1-2</option>
</select>
If all of your selects have a common class you can just use one selector
const allSelectedText = Array.from(d3.selectAll('select.foo option:checked')).map(opt => opt.textContent);
console.log(allSelectedText);
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/7.3.0/d3.min.js" integrity="sha512-NMhzM2RHzbCRO0s5VPaRC+2bW6nmNXimzC9p5sp2x19M+zzuSJ2T50dEQ7hpHkNjnX1mt8nQg1NNthwRZgsoIg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<select class="foo">
<option>Hello 1-1 </option>
<option selected>Hello 1-2</option>
</select>
<select class="foo">
<option>Hello 2-1</option>
<option>Hello 2-2</option>
</select>
<select class="foo">
<option>Hello 3-1</option>
<option>Hello 3-1</option>
</select>