I have a map in my java sevlet and converting it to a json format that works right.
When I do this function below it creates a drop down, but it puts every character
$(JSON.parse(response)).map(function () {
return $('<option>').val(this.value).text(this.label);
}).appendTo('#selectorId');
I believe this can help you:
$(document).ready(function(){
var temp = {someKey:"temp value", otherKey:"other value", fooKey:"some value"};
for (var key in temp) {
alert('<option value=' + key + '>' + temp[key] + '</option>');
}
});
I just used the javascript console in Chrome to do this. I replaced some of your stuff with placeholders.
var temp= ['one', 'two', 'three']; //'${temp}';
//alert(options);
var $select = $('<select>'); //$('#down');
$select.find('option').remove();
$.each(temp, function(key, value) {
$('<option>').val(key).text(value).appendTo($select);
});
console.log($select.html());
Output:
<option value="0">one</option><option value="1">two</option><option value="2">three</option>
However it looks like your json is probably actually a string because the following will end up doing what you describe. So make your JSON actual JSON not a string.
var temp= "['one', 'two', 'three']"; //'${temp}';
//alert(options);
var $select = $('<select>'); //$('#down');
$select.find('option').remove();
$.each(temp, function(key, value) {
$('<option>').val(key).text(value).appendTo($select);
});
console.log($select.html());
Only change the DOM once...
var listitems = '';
$.each(temp, function(key, value){
listitems += '<option value=' + key + '>' + value + '</option>';
});
$select.append(listitems);
That work fine in Ajax call back to update select from JSON object
function UpdateList() {
var lsUrl = '@Url.Action("Action", "Controller")';
$.get(lsUrl, function (opdata) {
$.each(opdata, function (key, value) {
$('#myselect').append('<option value=' + key + '>' + value + '</option>');
});
});
}
I would do something like this:
$.each(temp,function(key, value)
{
$select.append('<option value=' + key + '>' + value + '</option>');
});
JSON structure would be appreciated. At first you can experiment with find('element')
- it depends on JSON.