How to select dropdown list item by text

在網頁上實作""修改現有資料""時,一般要讓Dropdownlist選中本來的值,大多有以下二種作法
1. 在後端組資料時就賦予哪一個是Selected="true"
2. 用jQuery讓符合指定value的選項被選中
    寫法為 $("#Dropdownlist的ID").val("指定的值");

在Telerik Grid中也是採用第二種作法
function Grid_onEdit(e) {
    var dataItem = e.dataItem;
    var mode = e.mode;
    var form = e.form;
    var priceTextBox = $(form).find("#Price");

    var customerDropDownList = $(form).find("#Customer");
    if (mode == "edit") {
        //Select the proper dropdown list item
        customerDropDownList.val(dataItem.CustomerID);
    }
}

但是,當Dropdownlist的Text和Value不同時,
customerDropDownList.val(dataItem.CustomerID); 寫法是無效且不合理的
因為dataItem.CustomerID取回的是Dropdownlist的Text,但jQuery的val是用來比對Value

解決的寫法如下
$("select option:contains(" + dataItem.CustomerID+ ")").attr('selected', true); 

沒有留言: