Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery - How to populate dropdown/select/combobox dynamically?

I am trying to add a drop down in a div dynamically[jQuery] but its not working. I want following structure:

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

I have read this but it did not work.

Here is what I've tried:

$('#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");
});
like image 954
Baqer Naqvi Avatar asked Jan 01 '14 11:01

Baqer Naqvi


2 Answers

Check the bellow fiddle. This will help you. Change them according to your need.

$('#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);
});

$(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);
    
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="book_selection"></div>

you can also use jquery

$('#book_selection').change(function() {
    $("<select />").append($("<option>", {"value": "me", "text": "me"})).insertAfter($(this));
});
like image 79
A Paul Avatar answered Oct 13 '22 03:10

A Paul


try this

<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>        
    </select> 

to add a new option to the combobox you can try the following jQuery

<script>
function add(){
        var str="<option id='5'>Al-Tobah</option>"
        $("#surah_selection").append(str);
    }
</script>

by call this function a new option will be added to your Combobox

like image 32
Myth Avatar answered Oct 13 '22 03:10

Myth