Get value of Dynamically created select

Viewed 32

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)
1 Answers

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

Related