admin管理员组文章数量:1315288
I am using jQuery and have server code returning the following values
0:SELECT ONE;1:VALUE1;2:VALUE2 etc
How do I populate this into a select box?
var="0:SELECT ONE;1:VALUE1;2:VALUE2";
$("#targetSelectBox"). ???????
I am using jQuery and have server code returning the following values
0:SELECT ONE;1:VALUE1;2:VALUE2 etc
How do I populate this into a select box?
var="0:SELECT ONE;1:VALUE1;2:VALUE2";
$("#targetSelectBox"). ???????
Share
Improve this question
edited Nov 13, 2012 at 20:48
nalply
28.8k15 gold badges82 silver badges104 bronze badges
asked Jan 21, 2010 at 18:36
ShahShah
531 silver badge3 bronze badges
1
- 1 Please do not tag a javascript question with java. – Martijn Courteaux Commented Jan 21, 2010 at 18:45
4 Answers
Reset to default 5var opts = "0:SELECT ONE;1:VALUE1;2:VALUE2";
opts = opts.split(';');
var target = $("#targetSelectBox");
$.each(opts, function(i, opt){
opt = opt.split(':');
target.append($('<option />').val(opt[0].trim()).text(opt[1].trim()));
});
You can also use jquery's add() function.
For e.g.
var options = ["0":{"description":"Select an item"}, "1":{"description":"item 1"}];
var dropdown = $("#dropdown_id")[0];
$.each(options, function(i, item) {
var option = new Option(item.description, i);
if ($.browser.msie) {
dropdown.add(option);
}
else {
dropdown.add(option, null);
}
});
// Variable holding key-value pairs
var values = "1:VALUE;2:VALUE";
// Convert to an array of key-values
var vals = values.split(";");
// Cycle through each pair
for (var i = 0; i < vals.length; i++) {
// Split to get true key, and true value
var parts = vals[i].split(":");
// Append new option holding true key, and true value
$("#targetSelectBox").append($("option").val(parts[0]).text(parts[1]));
}
Its working fine in firefox but not in IE. I get "Object doesn't support property or method". Therefore I propose this solution:
var target = $("#targetSelectBox")
var vals = values.split(";");
for (var i = 0; i < vals.length; i++) {
var parts = vals[i].split(":");
target.append($('<option />').val(parts[0].trim()).text(parts[1].trim()));
}
本文标签: javascriptPopulate select box with keyvalue pairStack Overflow
版权声明:本文标题:javascript - Populate select box with key:value pair? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741978140a2408239.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论