Html select options appending

I am using the below code to convert the blockquote to the options of select element. enter image description here

Please help to make it right as each option. Thank you.

["Yes ?No", "one ?two ?three ?four", "person 1 ?person 2"]

var newArr = [];        
for (var i = 0; i < arr.length; i++) {
            var data = arr[i].split('\r\n');
            newArr.push(data);    
        }

for (var j = 0; j < newArr.length; j++) {
            $('#metadata-field').append('<select name=""></select>');
            if (newArr[j].length) {
                for (var k = 0; k < newArr[j].length; k++) {
                    $('#metadata-field select').append('<option>' + newArr[j][k] + '</option>');
                }
            } else {
                alert('No data');
            }
        }

Answers 1

  • Try this : You need to split array element using ? and then append each element using one loop only and not nested loop. See below code -

    var arr = ["Yes ?No", "one ?two ?three ?four", "person 1 ?person 2"]
        
    for (var i = 0; i < arr.length; i++) {
          var data = arr[i].split(' ?');
         //create select box
         var $select = $('<select id="' + i + '"></select>');
         $('#metadata-field').append($select);
         for(var k=0;k<data.length;k++)
          {
            //append options in select box
            $select.append('<option>' + data[k] + '</option>');
          }
      }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div id="metadata-field"></div>


Related Articles