Populate a Drop Down List From a Text File

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>
 
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>');
});
 
@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:
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 :)
 
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>');
});
 
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>');
 
Back
Top