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
Add a ment  | 

4 Answers 4

Reset to default 5
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()));
}

本文标签: javascriptPopulate select box with keyvalue pairStack Overflow