The_Outsider The_Outsider - 2 months ago 6
Javascript Question

Dropdown value not being retained

I have a dropdown which gets its value from a model and is first populated. On click of that dropdown, I populate other values using AJAX. I am able to populate the dropdown but once I select an option from the dropdown, it gets reset to first value in the dropdown. What I want is the dropdown to populate once on click and then function like a normal dropdown. How do I put a condition for it?

This is the code for initially setting the dropdown value with the defined value 'field.Value'

ddlValue = "<option value="+field.Value+ " selected='selected'>" + field.Value+"</option>";

<td><select id='@String.Format("selValue{0}", field.Field)' class='ddlValue'>@Html.Raw(ddlValue)</select></td>


And this is the AJAX function which populates it.

$('body').on('click', '.ddlValue', function () {
var target = event.target.id;
var rowId = $('#' + target).closest("tr").prop("id");
var field = $('#' + rowId).find(".fieldvalue").html();

$.ajax({
cache: false,
url: '@Url.Action("PopulateDropdown", "AdvancedSearch")',
type: "POST",
data: { Field: field }
}).done(function (data) {

var listb = $('#' + target);
listb.empty();

$.each(data.value, function (index, value) {
listb.append($('<option>', {
value: value,
text: value
}, '<option/>'))
});

});

});

Answer

If you want the ajax population to happen only once, you need to remove the event listener after it has occurred. Something like so:

$('.ddlValue').on('click', function () {

    $(this).off('click'); //This removes the event after it has happened once.

    var target = event.target.id;
    var rowId = $('#' + target).closest("tr").prop("id");
    var field = $('#' + rowId).find(".fieldvalue").html();

    $.ajax({
        cache: false,
        url: '@Url.Action("PopulateDropdown", "AdvancedSearch")',
        type: "POST",
        data: { Field: field }
    }).done(function (data) {

        var listb = $('#' + target);
        listb.empty();

        $.each(data.value, function (index, value) {
            listb.append($('<option>', {
                value: value,
                text: value
            }, '<option/>'))
        });

    });

});

Please note, the follow will not work:

$('body').on('click', '.ddlValue', function () {
    $(this).off('click');
    ...
Comments