[英]on selected value populating the dropdown list
I am having list of directories those are themes that has templates in it. 我有目录列表,这些目录是带有模板的主题。 I am listing the themes dropdown with list of themes when any theme get selected it will populate the other dropdown list with its(the selected theme's) templates.
当选择任何主题时,我将主题下拉列表与主题列表一起列出,它将使用其(所选主题的)模板填充另一个下拉列表。
here is my javascript code I am able to get the list of templates after selecting theme but when I am trying to change it, it is duplicating the values in the templates dropdown list. 这是我的javascript代码,选择主题后我可以获取模板列表,但是当我尝试更改它时,它正在复制模板下拉列表中的值。
$('#theme').on('change', function() { var selectedTheme = $(this).find('option:selected').val(); $.ajax({ url: '/admin/content/templates?theme=' + selectedTheme, type: 'GET', dataType: 'json', contentType: "application/json", data: JSON.stringify(selectedTheme), success: function(data) { console.log(data) $.each(data, function(idx, value) { $('#template').append('<option>' + value + '</option>'); }); }, error: function(data) { console.log("There are some errors") } }); });
here is my controller method to get the templates of a theme. 这是我获取主题模板的控制器方法。
// getting the list of available templates
@RequestMapping(value="/templates", produces="application/json")
@ResponseBody
List<String> getTemplates(@RequestParam("theme") String theme) {
String path = "src/main/webapp/WEB-INF/views/themes/" + theme
List<String> templates = []
new File(path).eachFileMatch(~/.*.twig/) { file->
file.path
templates.add(file.getPath())
}
templates
}
can anyone tell me why it is duplicating the values in the templates dropdown list ? 谁能告诉我为什么它要复制模板下拉列表中的值?
Try adding a line to clear the template dropdown before repopulating it: 尝试添加一行以清除模板下拉列表,然后重新填充它:
success: function(data) {
console.log(data)
$('#template').empty(); //<======
$.each(data, function(idx, value) {
$('#template').append('<option>' + value + '</option>');
});
},
You can store the data in a string and dump it with html
: 您可以将数据存储在字符串中并使用
html
转储:
var str = "";
$.each(data, function(idx, value) {
str += '<option>' + value + '</option>';
});
$('#template').html(str);
I assume this would be more performant compared to writing on every loop. 与在每个循环上编写代码相比,我认为这样做的性能更高。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.