Juanso87
Juanso87

Reputation: 1101

Set SELECT value after filling it with jQuery

I'm trying to populate a SELECT using jQuery and after it's populated set the value i want. I'm working with ASP.NET MVC 5.

The problem is the value doesn't get set

Here's my code:

$(document).ready(function () {
    //DropDownLists Initialization
    ListCategories(); //Populates the dropdownlist
    PreviousCategory(); //Sets DropDownList value to previous state (posted value)
});
function PreviousCategory() {
    var previousCategory = $("#PreviousCategory").val();
    if (previousCategory != null && previousCategory != '') {
        $("#IdCategory").val(previousCategory);
    }
}

$("#PreviousCategory") is a hidden input wich gets it's value server-side after a postback with the next code:

@if (ViewBag.Category!=null)
{
    @Html.Hidden("PreviousCategory",(object)ViewBag.Category);
}

Both functions work separately, the DropDownList gets populated flawlessly, but the value doesn't get set. If i trigger PreviousCategory() from another event (for example a button click), the value gets set perfectly.

I didn't think it was necessary to post ListCategories() code since it works well and you can just assume it fills the dropdownlist, though if anyone find it necessary let me know and i'll edit the post.

EDIT:

Here is ListCategories() code:

function ListCategories(){
    _idOrganigrama = $("#IdOrganigrama").val()
    _idTipoPedido = $("#IdTipoPedido").val()
    data = { idOrganigrama: _idOrganigrama, idTipoPedido: _idTipoPedido }
    $.post("ListCategories/", data, function (categoryList) {
        $("#IdCategoria").empty();
        $(categoryList).each(function () {
            $("<option />", {
                val: this.Id,
                text: this.Descripcion
            }).appendTo($("#IdCategory"));
        });
    });
}

By the way...$("#IdCategory") is the select.

Upvotes: 0

Views: 1689

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388326

The problem seems to be in the ListCategories where you might be using a async function like ajax to fetch data from server and populate the select.

So use a callback based solution like this

$(document).ready(function () {
    //DropDownLists Initialization
    ListCategories(PreviousCategory); //Populates the dropdownlist
    //Sets DropDownList value to previous state (posted value) after the values are loaded
});

function PreviousCategory() {
    var previousCategory = $("#PreviousCategory").val();
    if (previousCategory != null && previousCategory != '') {
        $("#IdCategoria").val(previousCategory);
    }
}

function ListCategories(callback) {
    //your ajax request to populate the select
    $.ajax({}).done(function () {
        //populate the select

        //then at the last call the callback method which will set the value
        callback()
    })
};

Upvotes: 1

Related Questions