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

113
Views
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 answers
Answer question

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 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!