Keith Keith - 29 days ago 10
CSS Question

how to append option to a select

I have a variable which contains a number. I'd like to append an option with the numeric value in each based on whatever the variable number is ( ie: if total equals 10, then I need to add 10 options to the select with each option containing the next numeric row value, so 1, 2, 3, 4...etc. I start off with one hard coded option, and then I need to add options dynamically for every case. I've tried a multitude of scripts but I"m getting " cannot use in operator to search for length.

https://jsfiddle.net/v1yyhfm8/

HTML

<select id="main">
<option selected>1</option>
</select>


I tried:

var total = dataSource.total();
for (var i = 1; 1 <= total; i++) {
var added = document.createElement('option');
var test = $('#main');
added.value = i;
added.innerHTML = i;
test.append(added);
}


and

var total = dataSource.total();
$.each(total, function (i, item) {
$('#main').append($('<option>', {
value: item.total,
text: item.text
}));
});

Answer

In your code, the for loop condition would be true always which leads to an infinite loop so change it to i <= total.

var total = dataSource.total();
for (var i = 1; i <= total; i++) {
    var added = document.createElement('option');
    var select1 = $('#main');
    added.value = i;
    added.innerHTML = i;
    select1.append(added);
}

var total = 10;
for (var i = 1; i <= total; i++) {
  var added = document.createElement('option');
  var select1 = $('#main');
  added.value = i;
  added.innerHTML = i;
  select1.append(added);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="main">
  <option selected>1</option>
</select>