ajax - Set Dropdown List Selected Value with jQuery -


i have created dropdown list in 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 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 please tell me how can select option value using jquery.

i have tried:

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

which doesn't work.

you need set value in success callback method of $.fn.ajax(), asynchronous , can use $.fn.val() set value of select.

use

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

Comments

Popular posts from this blog

jquery - How do you format the date used in the popover widget title of FullCalendar? -

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -