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, bu
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
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
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));
});
});
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));
});
}
});
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.