Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

140
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda