Eden WebStudio Eden WebStudio - 1 month ago 9
Javascript Question

Place array/multiselect data in modal after successful Ajax

I am making an Ajax call which returns an employee Name and Id. These are an array which I wish to make available in a multiselect box in a Modal pop up. I also wish to show selected value if possible?

My console log shows:

Object {employees: Object}
employees:Object
data: Array(2)
0: Object
id: 1
name: "Sam Test 1"
__proto__: Object
1: Object
id: 2
name: "Joe Test 2"
__proto__: Object


My ajax call is as follows:

$(document).ready(function() {
$('.editApptModal-button').click(function() {
var appointmentID = $(this).attr('data-appointmentID');
console.log(appointmentID);
$.ajax({
type: 'ajax',
method: 'get',
url: '/ajax',
async: false,
dataType: 'json',
success: function(response) {
console.log(response);
$.each(response.employees.data, function(key, value) {
$('select').append($("<option/>", {
value: key,
text: value
}));
});

$('#editApptModal').modal('show');
},
error: function(response) {
alert('Could not displaying data' + response);
}
});
});
});


So what do I need to do here to place id in option value and name in option text?

$.each(response.employee.data, function(key, value) {
$('select').append($("<option/>", {
value: key,
text: value
}));
});


Update
With
console.log(JSON.stringify(response));
:

{
"employees": {
"data": [{
"id": 1,
"name": "Sam Test 1"
}, {
"id": 2,
"name": "Joe Test 2"
}]
}
}


Select box

<select multiple="multiple" name="employees" class="form-control search-select">
<option value=""></option>
</select>

Dij Dij
Answer Source

you need to do something like this:

$.each(response.employees.data, function(key, value) {
    $('select').append($("<option>", {
     value: value.id,
     text: value.name
       }));
   });