views:

124

answers:

3

I am using jquery to the server code returns 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"). ???????
A: 
// 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]));
}
Jonathan Sampson
+2  A: 
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()));
});
prodigitalson
Should be $('<option/>') to create a new element. Otherwise you're updating the value and text of all <option> elements on the page.
CalebD
@CalebD: absolutely correct. fixed. good catch :-)
prodigitalson
A: 

its working fine in firefox but not in IE. "Object doesn't support property or method"

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