Define a selection box using a key: value pair?

I am using jQuery and have server code returning the following values

0:SELECT ONE;1:VALUE1;2:VALUE2 etc 

How to fill this in the selection box?

 var="0:SELECT ONE;1:VALUE1;2:VALUE2"; $("#targetSelectBox"). ??????? 
+4
source share
4 answers
 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())); }); 
+4
source

You can also use the jquery add () function.

For instance,

 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); } }); 
+1
source
 // 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])); } 
0
source

Works fine in firefox, but not in IE. I get "Object does not 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
source

Source: https://habr.com/ru/post/1299029/


All Articles