Click here to Skip to main content
15,908,274 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hello World! i'm just starting using html for web page and i want to populate the select option in html dynamically using javascript or jquery. What is the best way to achieve this. i make some google research, but this do not work unfortunaly. i tried it with the examples in the link below but it's not working for me. what i'm doing wrong in my code? I am open to other suggestions.

https://www.electrictoolbox.com/javascript-add-options-html-select/
[^]

What I have tried:

HTML
<select class="col-xs-3" name="list" id="list">
   <option value="" selected>  Select List</option>
</select>


and my JS look like:

JavaScript
<script language="javascript" type="text/javascript">
       var select = document.getElementById("list");
       select.options[select.options.length] = new Option('text 1', 'Value1');
 </script>


i don't know how to code it in jquery. Any idea is welcome. thank you for your help.
Posted
Updated 7-Apr-17 0:07am

1 solution

try this

var select = document.getElementById('list');
       var items = [{ text: 'text1', value: 'value1' }, { text: 'text2', value: 'value2' }, { text: 'text3', value: 'value3' }];
       var options = [];
       for (var i = 0; i < items.length; i++)
           options.push('<option value="' + items[i].text + '">' + items[i].text + '</option>');
       select.innerHTML = options.join('');


Demo: - JSFiddle[^]
 
Share this answer
 
v2
Comments
Member 12558924 7-Apr-17 6:56am    
Thank you a lot, but it still does not work on my side. maybe i've missed something. Should I include something else?
Karthik_Mahalingam 7-Apr-17 6:57am    
you should place the script at the bottom
<!DOCTYPE html>
<html> 
<body> 
    <select class="col-xs-3" name="list" id="list">
        <option value="" selected>  Select List</option>
    </select> 

    <script>
        var select = document.getElementById('list');
        var items = [{ text: 'text1', value: 'value1' }, { text: 'text2', value: 'value2' }, { text: 'text3', value: 'value3' }];
        var options = [];
        for (var i = 0; i < items.length; i++)
            options.push('<option value="' + items[i].text + '">' + items[i].text + '</option>');
        select.innerHTML = options.join('');

    </script>

</body>
</html>
Member 12558924 7-Apr-17 7:16am    
thanks alot it's work fine. and what can i do if i want it to an extern file so that it can be use for others html file?
Karthik_Mahalingam 7-Apr-17 7:17am    
just push the script portion to an external file and just refer the file to this html file.
if it works, please close this post.
Member 12558924 7-Apr-17 7:28am    
thank you for your help!!!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900