Populate a Drop Down List From a Text File

windhawk91

Well-Known Member
Adept
Oct 24, 2008
446
14
82
Hello,

I want to populate a drop down list in HTML from a text file based on my computer.

In the below code, 'item1' and 'item2' should be stored in a .txt file.

Please can anyone help me with the same.

Thank You.

<html>
<head>
<title>PhoneGap</title>
<script type="text/javascript" charset="utf-8" src="cordova-2.5.0.js"></script>
</head>
<body>
<h1>Hello PhoneGap</h1>
<select name="colors">
<option selected value="base">Please Select</option>
<option value="">item1</option>
<option value="">item2</option>
</body>
</html>
 

arunlakra15

Member
Disciple
Oct 29, 2011
76
1
18
26
Hyderabad
you can try using jquery. Access the text file contents using :
Code:
$.get('text_file.txt', function(data) {
    items = manipulate data to get items;
    $('select[name=colors]').append('<option value="">' + items + '</option>');
});
 

windhawk91

Well-Known Member
Adept
Oct 24, 2008
446
14
82
@arunlakra15

Hey,

Thanks for the reply but I don't know how exactly to implement this into my code.

Could you please give me step by step instructions?

Sorry I am asking for spoonfeeding.

Let us suppose I have a text file on my desktop situated in the directory C:/Desktop/list.txt. The contents of the text file are:
<option>item1</option>
<option>item2</option>

How can I go about implementing it?
 
Last edited by a moderator:

Rahul++

SuperUser
Adept
Aug 27, 2007
3,142
175
152
27
Pune
www.wrapcode.com
Save it in JSON format and parse it using JQuery :) Easiest way to parse data.

Use something like this -
Code:
$.getJSON('test.txt', function(data) {
 
  $.each(data, function(key, val) {
      $('#IDofUL').append('<li>'+val+'</li>');
  });
 
});
Explore functions on JQuery website :)
 

arunlakra15

Member
Disciple
Oct 29, 2011
76
1
18
26
Hyderabad
yeah, saving the data in json format would make it easier. Save your items in the text file as follows :
Code:
{
    "key1": "value1",
    "key2": "value2",
    "key3": "value3"
}
Then, use jQuery to populate your select list. Refer to jQuery getJSON function to understand how it works.
Code:
$.getJSON("textfile.txt", function( json ) {
    for(var key in json)
            $('select[name=colors]').append('<option value="' + key + '">' + json[key] + '</option>');
});
 

arunlakra15

Member
Disciple
Oct 29, 2011
76
1
18
26
Hyderabad
Use this :
Code:
$.each(json, function(key, value) {
    $('select[name=colors]').append('<option value="' + key + '">' + json[key] + '</option>');
});
instead of :
Code:
for(var key in json)
    $('select[name=colors]').append('<option value="' + key + '">' + json[key] + '</option>');