Divya
Divya

Reputation: 1213

Setting selected value of Dropdown List where the Options of Dropdown List are appended dynamically using Jquery

Please Help If anyone have solution.

I am using dependency Dropdown, Where on Selection of Dealer's Dropdown Customer's List is binded dynamically with Jquery.

While in Edit mode according to Dealer Value I'm calling a function in Document.Ready that Appends the Customer's list by getting data from Ajax call.

after this function executes I'm setting the selected value from options, but it is showing null/blank. with many solutions tried. I referred to many questions on this site but result is same. am i doing mistake anywhere?

<select id="ddlcustomerlstEdit" name="ddlcustomerlstEdit" class="form-control">
         <option value=""> -select Customer- </option>
</select>

Here is dynamic binding of List in function called within document.ready.

if (data != "Blank") {
      $("#ddlcustomerlstEdit").html("");
           var str = '<option value=""> -Select Customer- </option>';
           for (var i = 0; i < data.length; i++) {
               str += '<option value=' + data[i].CustomerID + '> ' + data[i].CustomerName + '</option>';
           }
                        $("#ddlcustomerlstEdit").append(str);
}

As soon as this function executes i'm setting the selected value.

var customerIdVal = $("#hdnCustomerID").val();
$('#ddlcustomerlstEdit option[value="' + customerIdVal+'"]').attr("selected", "true");
alert($("#ddlcustomerlstEdit").val());

$("#hdnCustomerID") this value is coming within model and the value it contains is present in <option> yet the alert coming is always null or blank.

Edit

enter image description here

Upvotes: 2

Views: 75

Answers (1)

Ankit Agarwal
Ankit Agarwal

Reputation: 30739

This should be working.

$(document).ready(function() {
  var data = [{
    'CustomerID': '2',
    'CustomerName': 'Test55'
  }];
  if (data != "Blank") {
    $("#ddlcustomerlstEdit").html("");
    var str = '<option value=""> -Select Customer- </option>';
    for (var i = 0; i < data.length; i++) {
      str += '<option value=' + data[i].CustomerID + '> ' + data[i].CustomerName + '</option>';
    }
    $("#ddlcustomerlstEdit").append(str);

    var customerIdVal = $("#hdnCustomerID").val();
    $('#ddlcustomerlstEdit option[value="' + customerIdVal + '"]').attr("selected", "true");
    alert($("#ddlcustomerlstEdit").val());
  }

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="ddlcustomerlstEdit" name="ddlcustomerlstEdit" class="form-control">
         <option value=""> -select Customer- </option>
</select>

<input type='hidden' value='2' id='hdnCustomerID' />

Upvotes: 1

Related Questions