user3191137
user3191137

Reputation: 135

Populating select element with external javascript file

Trying to popluate a dropdown box from a list of data from my js file. I've found a few examples out there but not exactly what I'm trying to do. I would like it to show 'DataText' in the drop down itself.

 <select id="select" </select>

script

 <script type="text/javascript" src="js/data/datafile.js"></script>

Could it not be done as simple as this?

    $(document).ready(function()
{
      $("#select").append(Mydata);​
});

file format

var Mydata=[{"ID":"00","DataText":"Text1"}, {"ID":"01","DataText":"Text2"}, {"ID":"02","DataText":"Test3"}]

Upvotes: 0

Views: 610

Answers (3)

Mathachew
Mathachew

Reputation: 2034

Sure it can be done, but you have to iterate over the data and add what's needed.

$(document).ready(function () {
    for (var i = 0, count= Mydata.length; i < count; i++) {
        $('<option>').val(Mydata[i].ID).text(Mydata[i].DataText).appendTo("#select");
    }
});

This is a quick solution, so add error checking. Also, just in case this isn't a bad paste job, the HTML provided is invalid. The opening select tag needs a >

Demo

Upvotes: 0

Ram
Ram

Reputation: 144689

I'd suggest:

$('#select').html(function(){
   return $.map(Mydata, function(v) {
      return '<option id='+ v.ID +'>'+ v.DataText +'</option>';
   }).join('');
});

http://jsfiddle.net/Y8eCy/

Upvotes: 2

Jorge Faianca
Jorge Faianca

Reputation: 791

You need to loop your data and then insert it into your select, in this case i needed to parse the data.

var Mydata='[{"ID":"00","DataText":"Text1"}, {"ID":"01","DataText":"Text2"}, {"ID":"02","DataText":"Test3"}]';

var data = $.parseJSON(Mydata);

    $.each(data, function(k,v){
     $('#test').append('<option value="'+v.ID+'">'+v.DataText+'</option>');
    });

Working example: jsfiddle

Upvotes: 0

Related Questions