2012年10月5日 星期五

{JavaScript} html-select option Postback後指定選取


Html:

<select name="ddlNo" id="ddlNo" style="width: 10%">
<% var No= ViewState["No"] as List<string>;%>
<% if (No!= null) %>
<% { %>
<%=         "<option value=''></option>"%>
<%      foreach (var item in No)%>
<%      { %>
<%=         "<option value=" + item + ">" + item + "</option>"%>
<%      } %>
<% } %>
</select>

C#:
//用一個Hidden將被選取的值記錄下來,以供PostBack後重新Load畫面給JS判斷用
string No = Request.Form["ddlNo"];
HiddenselectNo.Value = No ;


JS:
if ($('#<%=HiddenselectNo.ClientID%>').val() != '') {
                var selectObj = $('#ddlNo')[0];
                for (var i = 0; i < selectObj.length; i++) {
//當值相同時,則被選取,否則為False;預設是第一個是被選取
var selectObj = $('#ddlSupplierNo')[0];
for (var i = 0; i < selectObj.length; i++) {
    if (selectObj[i].text == $('#<%=HiddenselectNo.ClientID%>').val())
        selectObj[i].selected = true;
    else
        selectObj[i].selected = false;
}


參考資料:
http://www.xiaoxiaozi.com/2010/08/17/1856/