Walter Lockhart
Walter Lockhart

Reputation: 1293

Set Dropdown List Selected Value with jQuery

I have created a dropdown list in an ASP.NET MVC view using AJAX:

Url="/Channel/GetChannels";
$.ajax({
    url:Url,
    dataType: 'json',
    data: '',
    success: function (data) {
        $("#ddlChannel").empty();
        $("#ddlChannel").append("<option value='0'>All</option>");
        $.each(data, function (index, optiondata) {
            $("#ddlChannel").append("<option value='" + optiondata.Id + "'>" + optiondata.Name + "</option>");
        });
    }
});
$("#ddlChannel option[value='1']").attr("selected", "selected");

This produces the following markup:

<select id="ddlChannel">
<option value="0">All</option>
<option value="1">New Homes</option>
<option value="2">Sales</option>
<option value="3">Lettings</option>
</select>

Would someone please tell me how I can select an option value using jQuery.

I have tried:

$("#ddlChannel option[value='1']").attr("selected", "selected");

which doesn't work.

Upvotes: 0

Views: 18124

Answers (1)

Satpal
Satpal

Reputation: 133403

You need to set value in the success callback method of $.fn.ajax(), as it is asynchronous and also you can use $.fn.val() to set value of select.

Use

success: function (data) {
    //Your code
    $("#ddlChannel").val(1); 
}

Upvotes: 3

Related Questions