JQuery populates DropDownList with JSON data

Let's say I have this data returned from a basic service level:

["2", "3", "7", "14"]

First question. Is this considered valid JSON data? Json.org says it is, but I can not find any links to it in Google, SO, etc.

An ordered list of values. In most languages, this is implemented as an array, vector, list, or sequence.

I want to be able to accept these values ​​and add them to an existing DropDownList OnLoad object using jQuery.

$.getJSON("http://www.example.com/path-to-get-data", function(data) { //iterate through each object and add it to the list. //ideally, the key and value (string to display to the end user) would be the same. }); 

I looked at this stream , but it has objects, not just an array. Should I use parseJSON vs getJSON ?

Thanks in advance!

+6
source share
6 answers
 var arr = [ 2, 3, 7, 14]; $.each(arr, function(index, value) { ('#myselect').append($('<option>').text(value).attr('value', index)); }); 

Also pay attention to Mr. C.'s decision:

 $('<option></option>').val(item).html(item) 

His way of manipulating the option new to me and more elegant.

+9
source

My decision was based on Blaze's idea.

 //populate the Drop Down List $.getJSON("http://www.example.com/api/service", function (data) { $.each(data, function (index, item) { $('#dropDownList').append( $('<option></option>').val(item).html(item) ); }); }); 
+5
source

This is not JSON correct, it should be this style:

 {"0": "2", "1" : "3", "2" : "7", "3" : "14"} 

You can use this sample to fulfill the answer:

 var response = "[2, 3, 7, 14]"; eval("var tmp = " + response); console.log(tmp); 
+2
source

This is a HiddenField declaration that is useful for storing a JSON string.

  <asp:HiddenField ID="hdnBankStatus" runat="server" /> 

This is a Dropdownlist ad.

  <select id="optStatus" name="optStatus" runat="server"> </select> 

These lines initialize a Hiddenfield value with a sorted list (suppose the list contains pairs of key values ​​in sorted order), which is then serialized using the JSON serializer

  sl = new SortedList(); hdnBankStatus.Value = jsonSerialiser.Serialize(sl); 

These strings will use the JSON String Elements one by one and populate the dropdown menu with the values.

  $(document).ready(function () { var myOptions = $.parseJSON($('#hdnBankStatus').val()); var mySelect = $('#optStatus'); $.each(myOptions, function (val, text) { mySelect.append( $('<option></option>').val(text).html(val) ); }); } 
+1
source
  var arr = [ 2, 3, 7, 14]; var dropdown = ('#myselect'); dropdown.empty(); dropdown.append($('<option value=''>--Please Select--</option>')); $.each(arr, function(index, value) { dropdown.append($('<option value='+index+'>'+value+'</option>')); });` 
0
source

It worked for me.

 $("#ddlCaseType").append("<option>" + txt + "</option>"); 
-3
source

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


All Articles