Augustin Augustin - 1 month ago 10
jQuery Question

How to bind Dropdown list by changing item in another dropdown in mvc using jquery

I am trying to bind states based on country selection using jquery ajax and i am using just html select for states.

<select id="State" class="selectpicker" required>
</select>
@Html.DropDownList("Countries", (IEnumerable<SelectListItem>)ViewBag.CountryId, "Select", new { @class = "selectpicker", @readonly = "true" })

$('#Countries').on('change', function () {

var CountryId = $('#Countries').val();
$.ajax({
url: "/Home/GetStates",
data: JSON.stringify({
CountryId: CountryId
}),
contentType: "application/json; charset=utf-8",
dataType: "json",
type: "POST",

success: function (Result) {
$.each(Result, function (item,index) {
console.log(index);
$.each(index, function (i) {

//$('#State').append($("<option></option>")
// .attr("value", index[i].StateID)
// .text(index[i].StateName));

//$('#State').append($('<option>', {
// value: index[i].StateID,
// text: index[i].StateName
//}, '</option>'));

var optionhtml = '<option value="' +index[i].StateID + '">' + index[i].StateName + '</option>';
console.log(optionhtml);

$("#State").append(optionhtml);

//$("#State").append($("<option></option>").text(index[i].StateName).val(index[i].StateID));
});


});

error: function (request, status, error) {
alert("error occured -- "+request.responseText);
}

});
});


the problem only is data not displaying as options.I have used different ways to loop through my results and create my select id=State. (those are commented in the above code)

Answer
<select class="selectpicker"></select>

it seems to be you are using bootstrap,so to programmatically update a select with JavaScript, first manipulate the select, then use the refresh method to update the UI to match the new state. This is necessary when removing or adding options, or when disabling/enabling a select via JavaScript.

use this:
$("#State").append(optionhtml).selectpicker('refresh');