Reputation: 23
I have an array that I would like to use as options in my select dropdown menu. When I run the code, it only appends the first item of that array, and I am not sure why.
$.ajax({
type: 'post',
url: 'Reporting.aspx/actionType',
contentType: 'application/json; charset=utf-8',
data: '{ reportType: "' + reportType + '" }',
dataType: 'json',
success: function (r, re) {
$.each(r, function () {
testList.push(r.d)
})
for (var i = 0; i < testList.length; i++) {
$('#drpAction').append('<option>' + testList[0][i] + '</option>')
}
console.log(testList)
},
failure: function () {
swal({
title: 'Error',
text: 'There was an error loading the data',
confirmButtonText: 'OK'
})
}
})
Upvotes: 1
Views: 59
Reputation: 2590
you are looping through testList.length
but using testList[0][i]
.. try using testList[i]
instead, like i did here:
for (var i = 0; i < testList.length; i++) {
$('#drpAction').append('<option>' + testList[i] + '</option>')
}
but, if the items you want to show are inside testList[0]
, you have too loop through testList[0].length
instead of testList.length, like:
for (var i = 0; i < testList[0].length; i++) {
$('#drpAction').append('<option>' + testList[0][i] + '</option>')
}
if nothing of this is working, i have to see whats your testList
looks like.
Upvotes: 1
Reputation: 4755
I believe you have to loop through the items in testList[0]
var testList = [[1,2,3]]
for (var i = 0; i < testList[0].length; i++) {
$('#drpAction').append('<option>' + testList[0][i] + '</option>')
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="drpAction"></select>
Upvotes: 1
Reputation: 1459
Here is your problem testList[0][i]
, you are looping against testList
but you want to access to a list inside testList[0]
you should put the i
between the first brackets
$('#drpAction').append('<option>' + testList[i] + '</option>')
or check for testList[0].length
Upvotes: 0