2011-01-28 84 views
0

這裏是我有一個正確填充選擇列表:jquery設置選擇的選項;不適用於動態添加選項工作,但確實爲靜態的

  <select id="countriesList"> 
       <option value="0"> -- select country -- </option> 
       <option value="500"> 500 </option> 
      </select> 

      <script type="text/javascript"> 
       $(function() { 
        // load the countries list 
        $.getJSON(
         "/StaticData/GetAllCountries/", 
         function (countries) { 
          // iterate each returned country and add it to the countries select list. 
          $.each(countries, function (i, country) { 
           $("#countriesList").append("<option value='" + country.Id + "'>" + country.Description + "</option>"); 
          }); 
         }); 

        // set the selected country based on the model's delivered CountryId value 
        $('#countriesList').val(500); 
       }); 
      </script> 

人口的偉大工程,但在選擇的一個調用.VAL()由腳本添加的元素不會使其被選中,但作爲示例,靜態定義的選項「500」在我調用.val()時正常工作。

我對jQuery相當陌生,但沒有編程,因爲我進入瀏覽器編程。任何提示都會有用。你還需要什麼?

此腳本代碼直接位於表td標籤內,因此在呈現表單時填充並設置了選擇。

回答

3

嘗試做手工。

var select = document.getElementBydId("countriesList"); 
for (var i = 0; i < select.options.length; i++) { 
    if (select.options[i].value === "500") { 
     select.selectedIndex = i; 
    } 
} 

等等。問題是你做的Ajax和異步是,有一個回調

所以執行順序是:在選擇

  • 添加選項

    • 的getJSON
    • SETVAL選擇。

    所以添加$("#countriesList").val(500)到你的回調函數

  • +0

    謝謝。將.val()調用放在正確的位置後,完美地工作。那不是點擊。謝謝! – slimflem 2011-01-28 15:56:05

    +0

    你救了我的命!非常棒! – rubdottocom 2011-02-11 11:20:31

    1

    結束時,如果你想在同一地點你的例子.val(500)是選擇它,你永遠不會有一個工作的結果。 AJAX調用是異步進行的,並在.val(500)已被執行後填充信息。

    在ajax調用的返回函數中移動你的選擇,它應該工作正常。