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

json select option value
json dropdown selected value
dynamically populate a select element from json data with jquery
populate a select dropdown list using json
populate dropdown using jquery ajax json
how to populate values in dropdownlist using javascript
populate bootstrap dropdown with json data
populate dropdown using javascript from database

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>

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

How can I use JSON data to populate the options of a select box , Why not just make the server return the names? ["Woodland Hills", "none", "Los Angeles", "Laguna Hills"]. Then create the <option> elements  Line 1 targets the select element; Line 2 clears any options in the element; Lines 4-5 appends our default option; Line 10 defines the URL where we can find our JSON data; Lines 12-13 initializes the remote request ; Lines 19-24 creates an option element for each entry found and adds it to the select list; Line 34 sends the remote request


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

Populate a SELECT Dropdown List with JSON Data using JavaScript, Populate a SELECT Dropdown List with JSON Data using JavaScript + '</​option>'; } } function show(ele) { // GET THE SELECTED VALUE FROM <select>  Here's a demo showing how to populate or bind a SELECT element with JSON data dynamically using JavaScript.


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

Dynamically populate Year in DropDownList (SELECT) using jQuery, How do you display a selected value in a drop down list in HTML? Also Read: How to Use AngularJS ng-options to Bind or Populate JSON Array to a SELECT DropDownList. Extract Data from an External JSON File and Bind Data to <select> Element. The markup for this example remains the same as above.


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

Dynamically Bind or Populate SELECT Dropdown List with JSON , Dynamically Bind or Populate SELECT Dropdown List with JSON Data using jQuery to Use AngularJS ng-options to Bind or Populate JSON Array to a SELECT SELECT Dropdown List with JSON" id="bt" /> </p> <select id="sel"> <​option  I am using the same method here in this post showing an example on how to extract JSON data from an external file and bind or populate the data to a SELECT element using jQuery. With external file, I mean a .json file, stored locally or in the server.


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

Populate select options with JSON and jQuery, How to populate a drop-down/select options with JSON data in jQuery. listItems += "<option value = '" + jsonData.Table[i].stateid + "' >" + jsonData. What i want to achieve I have got one static select html options, these options do not change but will determine what the other select boxes output. Populate multiple select options with Json - jQuery Forum


JAVASCRIPT How to fill Select from JSON, Simple javascript exercise on how to fill select options from JSON file. to show how to Duration: 3:48 Posted: Sep 23, 2015 Then I use $.getJSON to make an ajax call and return the data as an JSON object: $.getJSON( "/Home/GetListViaJson" , null , function (data) { I then create an array and use jQuery's map function to iterate over the array, create each option element and add the text and value:


JSON, Here we have make dependent dropdown in jquery ajax using JSON data. It will be Dynamic Duration: 14:46 Posted: May 16, 2017 What im trying to do is populate the first box with the customers from the database, and then use the customerID to select all the vehicleID's from the database using the select.php script. What is happening is the customers box is getting selected but when the select a customer nothing happens. This is my Test.php file :


Populate SELECT options with Ajax., This is a JavaScript tutorial on how to populate a SELECT element's options with After that, I will take the returned JSON data and append each array element to We also added a default “loading” option, just to let the user know that they  We can add options to a list box by using records from a database table. Records from table will be returned in JSON string format and jQuery will be used to add options to list box. For this example we will keep three pages. You download all the files at the end of this page