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>

Answers 1

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


Related Articles