Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

115
Visualizações
Get value of Dynamically created select

I create a select box dynamically via an eventlistener.

<select name="s" id="s"></select>

becomes

<select name="s" id="s"><option value=1>1</option><option value=2>2</option>
<option value=3 selected="true">3</option></select>

I then call a js function to get the selected value. However it fails, the selectedOptions htmlcollection length is 0. But when I expand the collection I can see the selected value 0:<option value=3 selected=true> If i try to grab the value it fails e.selectedOptions[0].value If I make the dropdown static. I am able to retrieve the value.

e = document.querySelector('#s');
console.log(e.selectedOptions)
almost 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

I created the same scenario regarding your prob, you can check this out by simply using the document.getElementById

const form = document.getElementById("form");

const selectField = document.createElement("select");
selectField.setAttribute("id", "s");

// iterate the option/s
for(let i= 1; i <= 3; i++){
  const option = document.createElement("option");
  option.setAttribute("value", i);
  option.innerText = i;
  selectField.append(option);
}

// append the dynamic select field into div form as an example parent
form.append(selectField);

// this get the values from your dynamic select field
document.getElementById("s").onchange = function(e){
  console.log("value", e.target.value)
}


example: 
Input: select option 2
Output: "2"

my source: https://jsfiddle.net/d4q7mugh/12

almost 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda