如何动态填充下拉列表?

Baq*_*qvi 4 javascript jquery drop-down-menu

我试图在动态[jQuery]中添加一个div下拉但它不起作用.我想要以下结构:

<select id="surah_selection" style="position:relative; top:10px; left:25px"> 
      <option id="1">Select Surah</option> 
      <option id="2" >Al-Baqra</option>
      <option id="3">Al-Fatiha</option>
      <option id="4">Al-noor</option>
      <option id="5">Al-Tobah</option>
</select>  <!--Surah selection ends -->
Run Code Online (Sandbox Code Playgroud)

我已经读过这个但是没有用.

这是我尝试过的:

$('#book_selection').change(function(){
    alert("changed");
    var option = document.createElement("option");
    option.text = 'df';
    option.value = 'df';
    var temp = document.createElement('select');
    temp.appendChild(option);
    var root = document.getElementById('book_selection');
    root.appendChild(temp);
    alert("done");
});
Run Code Online (Sandbox Code Playgroud)

A P*_*aul 9

检查波纹管小提琴.这会对你有所帮助.根据您的需要更改它们.

$('#book_selection').change(function(){
    var newSelect=document.createElement('select');
    var selectHTML="";
    for(i=0; i<choices.length; i=i+1){
        selectHTML+= "<option value='"+choices[i]+"'>"+choices[i]+"</option>";
    }

    newSelect.innerHTML= selectHTML;
    document.getElementById('book_selection').appendChild(newSelect);
});
Run Code Online (Sandbox Code Playgroud)

$(document).ready(function(){
var newSelect=document.createElement('select');
    var selectHTML="";
   /* for(i=0; i<choices.length; i=i+1){
        selectHTML+= "<option value='"+choices[i]+"'>"+choices[i]+"</option>";
    }*/
    selectHTML+= "<option value='test'>test</option>";

    newSelect.innerHTML= selectHTML;
    document.getElementById('book_selection').appendChild(newSelect);
    
});
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="book_selection"></div>
Run Code Online (Sandbox Code Playgroud)

你也可以使用jquery

$('#book_selection').change(function() {
    $("<select />").append($("<option>", {"value": "me", "text": "me"})).insertAfter($(this));
});
Run Code Online (Sandbox Code Playgroud)