Reputation: 135
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
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 >
Upvotes: 0
Reputation: 144689
I'd suggest:
$('#select').html(function(){
return $.map(Mydata, function(v) {
return '<option id='+ v.ID +'>'+ v.DataText +'</option>';
}).join('');
});
Upvotes: 2
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