prestondoris
prestondoris

Reputation: 329

For Loop functionality wont work to append <option> to a <select> tag

I do not understand why the code that is commented out works to append an option to the select tag, but when I try to create an array and use a for loop to add all values of the array as options, the code does not work. If I am missing something simple, I apologize. Thank you in advance.

//var testing ="testing value"
//$('#test').append('<option>'+testing+'</option>');

var testArray = ['test1', 'test2', 'test3'];

for(var i=0, i < testArray.length, i++) {
  var value = testArray[i];
  $('#test').append('<option>'+value+'</option>');
  }
<script src='https://code.jquery.com/jquery-3.1.0.min.js'></script>
<select id="test">
  <option>--</option>
</select>

Upvotes: 0

Views: 1484

Answers (2)

4b0
4b0

Reputation: 22323

Problem is , . Define variable out side the loop and append markup once.

 var testArray = ['test1', 'test2', 'test3'];
 var html = '';
 for (var i = 0; i < testArray.length; i++) {
   var value = testArray[i];
   html += '<option>' + value + '</option>';
 }
 $('#test').append(html);
<script src='https://code.jquery.com/jquery-3.1.0.min.js'></script>
<select id="test">
  <option>--</option>
</select>

Upvotes: 1

Harsha W
Harsha W

Reputation: 3366

Try this

$.each(testArray, function(key, value) {   
 $('#test')
      .append($('<option>', { value : key })
      .text(value)); 
});

Upvotes: 0

Related Questions