Home > front end >  Append options in select from a list
Append options in select from a list

Time:02-07

let's say I am having a list like:

function main(vara) {
  var myStringArray = vara;
  var arrayLength = vara.length;
  for (var i = 0; i < arrayLength; i  ) {
    var option = myStringArray[i];
    document.getElementById("standard-select").innerHTML  = option;
  };
};

const valued = ['<option value="1">Some Value</select>', '<option value="2" >Some Value 2</select>', '<option value="3">Some Value 3</select>'];

main(valued);
<div  id="question">
  <label for='standard-select'>Select a preferred option</label>
  <div class='select'>
    <select id='standard-select'></select>
    <span class='class1'></span>
  </div>
  <div class='class2'>
    <input type='button' value='Button_Text' />
  </div>
</div>

But this doesn't seem working ?

CodePudding user response:

Code works as expected

https://jsbin.com/rasahas/1/edit?html,js,output

One thing you might be missing, Is write javascript after HTML do that DOM content is loaded before JS executes

SO something like

<div  id="question">
  <label for='standard-select'>Select a preferred option</label>
  <div class='select'>
    <select id='standard-select'></select>
    <span class='class1'></span>
  </div>
  <div class='class2'>
    <input type='button' value='Button_Text' />
  </div>
</div>

<script>
function main(vara) {
  var myStringArray = vara;
  var arrayLength = vara.length;
  for (var i = 0; i < arrayLength; i  ) {
    var option = myStringArray[i];
    document.getElementById("standard-select").innerHTML  = option;
  };
};

const valued = ['<option value="1">Some Value</select>', '<option value="2" >Some Value 2</select>', '<option value="3">Some Value 3</select>'];

main(valued);
</script>

CodePudding user response:

You made a mistaken with the closing tags so just change valued to this

['<option value="1">Some Value</option>',
'<option value="2" >Some Value 2</option>',
'<option value="3">Some Value 3</option>']

And I think it's better to make a new option element and append it to select as a child instead of updating the innerHtml directly with static data

  •  Tags:  
  • Related