How to Populate the Options of a Select Element in JavaScript

How to populate the options of a select element in javascript

You can create the option inside the loop;

for(element in langArray)
{
var opt = document.createElement("option");
opt.value= index;
opt.innerHTML = element; // whatever property it has

// then append it to the select element
newSelect.appendChild(opt);
index++;
}

// then append the select to an element in the dom

2023 Update:

To make sure we avoid creating globals and remain in the correct scope, we can use map() and let.

let selectTag = document.createElement('select');
langArray.map( (lang, i) => {
let opt = document.createElement("option");
opt.value = i; // the index
opt.innerHTML = lang;
selectTag.append(opt);
});

How to populate select option:select dynamically

The proper way is as follows

<select name="cakesize" class="custom-select cakesize">

<option value="<%=cake.item.price['1000'] %>" <%=cake.currentPrice == cake.item.price['1000'] ? 'selected' : '' %> >1kg</option>
<option value="<%=cake.item.price['1500'] %>" <%=cake.currentPrice == cake.item.price['1500'] ? 'selected' : '' %> >1.5kg</option>
<option value="<%=cake.item.price['2000'] %>" <%=cake.currentPrice == cake.item.price['2000'] ? 'selected' : '' %> >2kg</option>
<option value="<%=cake.item.price['2500'] %>" <%=cake.currentPrice == cake.item.price['2500'] ? 'selected' : '' %> >2.5kg</option>
<option value="<%=cake.item.price['3000'] %>" <%=cake.currentPrice == cake.item.price['3000'] ? 'selected' : '' %> >3kg</option>
<option value="<%=cake.item.price['3500'] %>" <%=cake.currentPrice == cake.item.price['3500'] ? 'selected' : '' %> >3.5kg</option>
<option value="<%=cake.item.price['4000'] %>" <%=cake.currentPrice == cake.item.price['4000'] ? 'selected' : '' %> >4kg</option>
<option value="<%=cake.item.price['4500'] %>" <%=cake.currentPrice == cake.item.price['4500'] ? 'selected' : '' %> >4.5kg</option>
<option value="<%=cake.item.price['5000'] %>" <%=cake.currentPrice == cake.item.price['5000'] ? 'selected' : '' %> >5kg</option>

</select>

Javascript populate select option from json

For some reason, the for loop was not clearing all the options, but I was able to achieve clearing all the options with a while loop:

while (select.options.length > 0) {
select.remove(0);
}

Here is the whole code (the only thing different is that I changed your for loop that clears the options for my while loop:

var data2 = {
"sistemi": {
"scorr_vel_class_": {
"maxL": 110,
"maxH": 270,
"vetro": ["Trasparente", "Trasp satinato", "Stampa digitale"]
},
"scorr_vel_minimal_": {
"maxL": 110,
"maxH": 270,
"vetro": ["Trasparente", "Trasp satinato", "Extrachiaro"]
}
}
}

function loadLista() {
var select = document.getElementById("selezionaVetro");
var opzioni = data2.sistemi[document.getElementsByName("Tipo_sistema")[0].value].vetro;

while (select.options.length > 0) {
select.remove(0);
}

for (var i = 0; i < opzioni.length; i++) {
var opt = opzioni[i];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
select.appendChild(el);
}
}

Credit goes to Rodrigo Longo in this post: https://stackoverflow.com/a/16107213/9454233

How to populate select option using api

The Problem:

your students object is empty before the API call and was not initialized in your setState. so using students.map in your select element will cause the error (since you can't map through an undefined array).

The Solution:

There are two important things before using the map with arrayes:

  1. check for the definition of the array (is the array defined and exists?)
  2. check its length (is the array has some content?)

First

check its declaration/definition by a simple if statement:

{
if(myArrayOfData) {
myArrayOfData.map(
// rest of the codes ...
)
}
}

Or with using ? shorthanded of if

{
myArrayOfData?.map(
// rest of the codes ...
)
}

Second

check for the contents of the array and use the map function after checking its length (which tells you the data has arrived from the API call etc. and is ready to process)

{
if(myArrayOfData) {
if(myArrayOfData.length > 0) {
myArrayOfData.map(
// rest of the codes ...
)
}
}
}

Finally:

while the above snippet works properly, you can simplify it by checking both if conditions together:

{
if(myArrayOfData?.length > 0) {
myArrayOfData.map(
// rest of the codes ...
)
}
}

Optional:

In real-world examples, you may need to show some loading components while the data is fetching.

{
if(myArrayOfData?.length > 0) {
myArrayOfData.map(
// rest of the codes ...
)
} else {
<Loading />
}
}
Be Aware
const anEmptyArray  = []

if(anEmptyArray){
// rest of the codes ...
}

The result of comparison on if(anEmptyArray) is always true with an empty array.

How to populate a dynamically created select with options

You need to declare this ( current select-box) outside your ajax call and then access your select-box like below :

var selector = $(this); //declare this
$.ajax({
//..
.done (function(responseJson1a){
//other codes
selector.closest('tr').find('.activityClass').html(activityOptionsNew);//add htmls
})

How to populate a select element with dynamic values in JQuery?

You have malformed html in $("<option</option>"). The opening tag is missing a >

Try

var rateArr=[5,2,2,3,5]
$('.rating').each(function(index,row){ for(var i=1; i<= rateArr[index]; i++){ $(this).append($("<option>").text(i).val(i)); }});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><select class="form-control rating"></select><select class="form-control rating"></select><select class="form-control rating"></select><select class="form-control rating"></select><select class="form-control rating"></select>


Related Topics



Leave a reply



Submit