[javascript] How can I use JSON data to populate the options of a select box?

I need to feed cities based on country of selection. I did it programmically but have no idea how to put JSON data into the select box. I tried several ways using jQuery, but none of them worked.

The response I am getting (I can format this differently if necessary):

["<option value='Woodland Hills'>Woodland Hills<\/option>","<option value='none'>none<\/option>","<option value='Los Angeles'>Los Angeles<\/option>","<option value='Laguna Hills'>Laguna Hills<\/option>"]

But how can I put this data as options inside a HTML <select></select> tag?

The code I tried:

<form action="" method="post">
<input id="city" name="city" type="text" onkeyup="getResults(this.value)"/>
<input type="text" id="result" value=""/>
<select id="myselect" name="myselect" ><option selected="selected">blank</option></select>
</form>
</div>

<script>
function getResults(str) {
  $.ajax({
        url:'suggest.html',
        type:'POST',
        data: 'q=' + str,
        dataType: 'json',
        success: function( json ) {
            $('#myselect').append(json);

        }
    });
};

$( '.suggest' ).keyup( function() {
   getResults( $( this ).val() );
} );
</script>

I also tried to use this tutorial on auto-populating select boxes using jQuery and AJAX, but this never did anything except filling my select with "UNDEFINED" for me even though I got the response in the format the tutorial suggested.

<script type="text/javascript" charset="utf-8">
$(function(){
  $("select#city").change(function(){
    $.getJSON("/select.php",{id: $(this).val(), ajax: 'true'}, function(j){
      var options = '';
      for (var i = 0; i < j.length; i++) {
        options += '<option value="' + j[i].optionValue + '">' + j[i].optionDisplay + '</option>';
      }
      $("select#myselect").html(options);
    })
  })
})
</script>

This question is related to javascript jquery html json

The answer is


Take a look at JQuery view engine and just load the array into a dropdown:

$.ajax({
    url:'suggest.html',
    type:'POST',
    data: 'q=' + str,
    dataType: 'json',
    success: function( json ) {
          // Assumption is that API returned something like:["North","West","South","East"];
          $('#myselect').view(json);
    }
});

See details here: https://jocapc.github.io/jquery-view-engine/docs/ajax-dropdown


You should do it like this:

function getResults(str) {
  $.ajax({
        url:'suggest.html',
        type:'POST',
        data: 'q=' + str,
        dataType: 'json',
        success: function( json ) {
           $.each(json, function(i, optionHtml){
              $('#myselect').append(optionHtml);
           });
        }
    });
};

Cheers


Why not just make the server return the names?

["Woodland Hills", "none", "Los Angeles", "Laguna Hills"]

Then create the <option> elements using JavaScript.

$.ajax({
    url:'suggest.html',
    type:'POST',
    data: 'q=' + str,
    dataType: 'json',
    success: function( json ) {
        $.each(json, function(i, value) {
            $('#myselect').append($('<option>').text(value).attr('value', value));
        });
    }
});

Given returned json from your://site.com:

[{text:"Text1", val:"Value1"},
{text:"Text2", val:"Value2"},
{text:"Text3", val:"Value3"}]

Use this:

    $.getJSON("your://site.com", function(json){
            $('#select').empty();
            $('#select').append($('<option>').text("Select"));
            $.each(json, function(i, obj){
                    $('#select').append($('<option>').text(obj.text).attr('value', obj.val));
            });
    });

zeusstl is right. it works for me too.

   <select class="form-control select2" id="myselect">
                      <option disabled="disabled" selected></option>
                      <option>Male</option>
                      <option>Female</option>
                    </select>

   $.getJSON("mysite/json1.php", function(json){
        $('#myselect').empty();
        $('#myselect').append($('<option>').text("Select"));
        $.each(json, function(i, obj){

  $('#myselect').append($('<option>').text(obj.text).attr('value', obj.val));
        });
  });

I know this question is a bit old, but I'd use a jQuery template and a $.ajax call:

ASPX:
<select id="mySelect" name="mySelect>
    <option value="0">-select-</option>
</select>
<script id="mySelectTemplate" type="text/x-jquery-tmpl">
    <option value="${CityId}">${CityName}</option>
</script>

JS:
$.ajax({ 
    url: location.pathname + '/GetCities', 
    type: 'POST', 
    contentType: 'application/json; charset=utf-8', 
    dataType: 'json', 
    success: function (response) { 
        $('#mySelectTemplate').tmpl(response.d).appendTo('#mySelect'); 
    } 
});

In addition to the above you'll need a web method (GetCities) that returns a list of objects that include the data elements you're using in your template. I often use Entity Framework and my web method will call a manager class that is getting values from the database using linq. By doing that you can have your input save to the database and refreshing your select list is as simple as calling the databind in JS in the success of your save.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?