Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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> 
like image 671
Pizdabol Avatar asked May 06 '11 23:05

Pizdabol


People also ask

How do you populate values in one HTML dropdown list with another using simple JavaScript?

ready(function () { var list1 = document. getElementById('firstList'); list1. options[0] = new Option('--Select--', ''); list1. options[1] = new Option('Snacks', 'Snacks'); list1.


1 Answers

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));         });     } }); 
like image 179
Samir Talwar Avatar answered Sep 19 '22 18:09

Samir Talwar