Reputation: 336
I am using script as follows.. I need to print names in option to display..
$.ajax({
url: "https://n2s.herokuapp.com/api/post/get_all_category/",
method: "GET",
dataType: "JSON",
success: function(e) {
console.log(e);
$('.selectpicker').selectpicker();
for (var i = 0; i < 10; i++) {
var o = new Option("option text"+i, "value"+i);
/// jquerify the DOM object 'o' so we can use the html method
$(o).html("e.name"+i);
$(".selectpicker").append(o);
}
$(".selectpicker").selectpicker('refresh');
vm.articles = e;
console.log(vm);
},
});
I am a beginner in js and does not have much knowknowlede.. Can anybody please help me to print the names in the above code.
My json data is as
[
{"name": "Health care", "cat_id": 1
{"name": "Education", "cat_id": 2
{"name": "Bakery", "cat_id": 3
{"name": "Software company", "cat_id": 4
{"name": "Automobile", "cat_id": 5
{"name": "Agriculture", "cat_id": 6
{"name": "Marketing", "cat_id": 7
{"name": "Multimedia", "cat_id": 8
{"name": "Electrical Shop", "cat_id": 9
{"name": "AutoTaxi", "cat_id": 10
{"name": "Workshop", "cat_id": 11
{"name": "Engineering Work", "cat_id": 12
{"name": "Medical Shop", "cat_id": 13
{"name": "Lathe", "cat_id": 14
{"name": "Hotel", "cat_id": 15}
]
Upvotes: 0
Views: 51
Reputation: 11472
In your question, there are missing some relevant parts(HTML
code, Bootstrap
files, etc), but I tried to replicate your issue and you can use e[i].name
to get the names from the json
. Also, you can use Object.keys(e).length
to get the actual length of the json
and parse it correctly:
$.ajax({
url: "https://n2s.herokuapp.com/api/post/get_all_category/",
method: "GET",
dataType: "JSON",
success: function(e) {
console.log(e);
$('.selectpicker').selectpicker();
//replaced i < 10 with i < Object.keys(e).length
for (var i = 0; i < Object.keys(e).length; i++) {
var o = new Option(e[i].name, "value" + i);
$(".selectpicker").append(o);
}
$(".selectpicker").selectpicker('refresh');
}
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.4/css/bootstrap-select.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.4/js/bootstrap-select.min.js"></script>
<select class='selectpicker'>
</select>
Upvotes: 1
Reputation: 34107
Try this
for (var i = 0; i <= e.length; i++) {
var o = new Option(e[i].name, "value"+i);
$(".selectpicker").append(o);
}
Upvotes: 0