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>
ready(function () { var list1 = document. getElementById('firstList'); list1. options[0] = new Option('--Select--', ''); list1. options[1] = new Option('Snacks', 'Snacks'); list1.
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)); }); } });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With