Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

139
Views
Cannot push strings set by variable to Javascript array

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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!