title: How can I use JSON data to populate the options of a select box?
body: <p>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.</p>
  
  <p>The response I am getting (I can format this differently if necessary):</p>
  
  <pre><code>["&lt;option value='Woodland Hills'&gt;Woodland Hills&lt;\/option&gt;","&lt;option value='none'&gt;none&lt;\/option&gt;","&lt;option value='Los Angeles'&gt;Los Angeles&lt;\/option&gt;","&lt;option value='Laguna Hills'&gt;Laguna Hills&lt;\/option&gt;"]
  </code></pre>
  
  <p>But how can I put this data as options inside a HTML <code>&lt;select&gt;&lt;/select&gt;</code> tag?</p>
  
  <p>The code I tried:</p>
  
  <pre><code>&lt;form action="" method="post"&gt;
  &lt;input id="city" name="city" type="text" onkeyup="getResults(this.value)"/&gt;
  &lt;input type="text" id="result" value=""/&gt;
  &lt;select id="myselect" name="myselect" &gt;&lt;option selected="selected"&gt;blank&lt;/option&gt;&lt;/select&gt;
  &lt;/form&gt;
  &lt;/div&gt;
  
  &lt;script&gt;
  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() );
  } );
  &lt;/script&gt;
  </code></pre>
  
  <p>I also tried to use this <a href="http://remysharp.com/2007/01/20/auto-populating-select-boxes-using-jquery-ajax/" rel="noreferrer">tutorial on auto-populating select boxes using jQuery and AJAX</a>, 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.</p>
  
  <pre><code>&lt;script type="text/javascript" charset="utf-8"&gt;
  $(function(){
    $("select#city").change(function(){
      $.getJSON("/select.php",{id: $(this).val(), ajax: 'true'}, function(j){
        var options = '';
        for (var i = 0; i &lt; j.length; i++) {
          options += '&lt;option value="' + j[i].optionValue + '"&gt;' + j[i].optionDisplay + '&lt;/option&gt;';
        }
        $("select#myselect").html(options);
      })
    })
  })
  &lt;/script&gt;
  </code></pre>