选择具有select2()属性的drowdown列表的值

时间:2015-08-25 12:50:25

标签: javascript jquery html twitter-bootstrap

在我的MVC视图中,我想根据我从模型中获得的值来选择选项。我尝试了如下,但是当我添加bootstrap 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>

1 个答案:

答案 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");

<强>样本...

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

$yourSelect.select2();

$yourSelect.val("3").trigger("change");
&#13;
<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>
&#13;
&#13;
&#13;