Del Monte
Del Monte

Reputation: 153

How to set the data in AJAX success function?

I have an ajax call that is returning me the data to be populated in a drop down list. Now, I need to be able to select a value which is returned and set the value of the drop down in the same function if possible. But by using $("#idOfDropDown").val(data), it is not getting set i.e While I am submitting the data, in the database all the options that were returned and populated are getting submitted and not the selected option. So, How do I set the selected value only?

Here's my AJAX function:

$.ajax({
  type: "POST",
  dataType: 'json',
  url: "/Controller/Action",
  data: {
    param: param,
  },
  success: function(data) {
    if (data.Response == "Unsuccessful") {
      console.log("Unsuccessful");
    } else if (data.Response == "Successful" || data.Response == "ConditionallySuccessful") {
      for (var i = 0; i < data.ExteriorColor.Data.length; i++) {
        $("#Exterior_Color").append($("<option></option>").val(data.ExteriorColor.Data[i]).html(data.ExteriorColor.Data[i]));
        console.log(data.ExteriorColor.Data[i]);
      }
      var html = '<ul>'
      for (var i = 0; i < data.Options.length; i++) {
        html += '<li>' + data.Options[i] + '</li>';
      }
      html += '</ul>'
      $("#twoColumnOptions").append(html);
      $("#twoColumnOptions").data(html);
      $("#Options").val(data.Options); 
      $("#Exterior_Color").val(data.ExteriorColor.Data).change(); //Value to be changed
      if (data.ExteriorColor.isInstalled == true)
        $("#Exterior_Color").attr("disabled", true);

    }

  },
  error: function(result) {
    console.log("Error while fetching data");
  }
});

Upvotes: 0

Views: 3349

Answers (2)

Zakaria Acharki
Zakaria Acharki

Reputation: 67505

Try to trigger the change you made using .trigger('change') like:

$("#Options").val(data.Options).trigger('change');
//Or
$("#Options").val(data.Options).change();

Upvotes: 1

Frank Odoom
Frank Odoom

Reputation: 1566

I implemented something similar in my solution and my code is like this, you need to set the value like this:

  success: function (response) {
                var array = response;
                if (array != '') {
                    for (i in array) {
                        $("#district").append("<option value='"+ 
                       array[i].Id + "'>" + array[i].DistrictName + "</option>");
                        }
                    }
                },

Upvotes: 0

Related Questions