javascript jQuery:尝试附加选项以选择标记
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29714114/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery:Trying to append the options to select tag
提问by Shaggie
Hi I am trying to append the options based on input to select tag. but options are not appending. I am not even getting the errors so where is the fault not able to understand.
嗨,我正在尝试根据输入附加选项以选择标签。但选项没有附加。我什至没有收到错误,所以无法理解错误在哪里。
HTML
HTML
<div class="col-lg-5">
<div class="input-group">
<label>Select type of Graph</label>
<select data-placeholder="Select Field..." id="graph_name" style="width:300px;" name="team_name" class="chosen-select" tabindex="2">
</select>
</div>
</div>
jQuery:
jQuery:
$('#field_name').change(function() {
var fieldname = $('#field_name option:selected').val();
$.post('<?php echo BASE_URL . 'php/processing/formDashboard/graph/showPossibleGraphs.php?id=' . $_GET['id']; ?>', {fieldname: fieldname}, function(data) {
$.each(data.graphs, function(index, value) {
$.each(value, function(index, value) {
console.log(value.id);
console.log(value.text);
var option = '<option value="'+value.id+'">'+value.text+'</option>';
$('#graph_name').append(option);
});
});
});
});
Here is the screenshot
这是屏幕截图
This is the image when i selected the option from one dropdown & the data came from script in JSON format
这是我从一个下拉列表中选择选项时的图像,数据来自 JSON 格式的脚本
This is the firebug debugging screenshot that shows that data is getting appended but on click it is showing nothing My sample data is this:
这是萤火虫调试屏幕截图,显示数据正在附加,但单击时它什么也没显示我的示例数据是这样的:
sample data: {
"status":"OK",
"response":200,
"graphs":[[
{"id":"B","text":"Bar Chart"},
{"id":"D","text":"Doughnut Chart"},
{"id":"P","text":"Pie Chart"}
]]
}
采纳答案by mohamedrias
EDIT Based on Chat
基于聊天的编辑
Since you're dynamically forming the select
, you must trigger the chosen plugin.
由于您正在动态形成select
,因此您必须触发所选插件。
$('#graph_name').trigger("chosen:updated");
Add it after appending the options. It will work
添加选项后添加它。它会工作
You're trying to append the string directly. But you must append the DOM element.
您正在尝试直接附加字符串。但是您必须附加 DOM 元素。
var option = '<option value="'+value.id+'">'+value.text+'</option>';
$('#graph_name').append(option);
It must be
一定是
var option = $('<option value="'+value.id+'">'+value.text+'</option>');
$('#graph_name').append(option);
Even better, instead of appending to the DOM tree on every iteration. Load it an array and then set the html() in the select
. It will improve the performance.
更好的是,而不是在每次迭代时附加到 DOM 树。加载一个数组,然后在select
. 它会提高性能。
回答by andybeli
Another alternative would be:
另一种选择是:
$.each(selectValues, function(key, value) {
$('#graph_name')
.append($("<option></option>")
.attr("value",key)
.text(value));
});