开发者

Populate select box with key:value pair?

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?

开发者_C百科var="0:SELECT ONE;1:VALUE1;2:VALUE2";
$("#targetSelectBox"). ???????


var 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()));
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜