2015-08-25 53 views
0

在我的MVC視圖中,我想根據從模型獲得的值選擇選項。我按照下面的方法試過,但是當我添加bootstrap select2()函數來選擇標籤時,它不會選擇值。選擇具有select2()屬性的下沉列表的值

<select style="width: 100%;" disabled="disabled" id="PositionId"> 
    <option value="0">---Select Position---</option> 
    <option value="1">1st</option> 
    <option value="2">2nd</option> 
    <option value="3">3rd</option> 
</select> 

<script> 
    $('#PositionId').select2(); 
    //not working with select2() 
    $('#PositionId option[value="@Model.CertificatePositionNo"]').attr("selected", "selected"); 
    //$('#PositionId').val("@Model.CertificatePositionNo"); 
</script> 
+0

是什麼錯誤? –

回答

0

你需要更新你的select元素的值,則觸發更改事件:

// Cache your element in a variable to allow access later... 
$yourSelect = $('#PositionId'); 

// Initialise... 
$yourSelect.select2(); 

// Update value and trigger 'change' event 
$yourSelect.val("@Model.CertificatePositionNo").trigger("change"); 

DEMO ...

var $yourSelect = $("#PositionId"); 
 

 
$yourSelect.select2(); 
 

 
$yourSelect.val("3").trigger("change");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<link href="http://select2.github.io/select2/select2-3.5.1/select2.css" rel="stylesheet"/> 
 
<script src="http://select2.github.io/select2/select2-3.5.1/select2.js"></script> 
 

 

 
<select id="PositionId"> 
 
    <option value="-1">Please select...</option> 
 
    <option value="1">Option 1</option> 
 
    <option value="2">Option 2</option> 
 
    <option value="3">Option 3</option> 
 
    <option value="4">Option 4</option> 
 
</select>

+0

我想在加載時更新 –

+0

這將在加載時更新。看演示 – Turnip

相關問題