我使用所选的插件从数据库中加载的数据中选择多个项目。这是保存的,然后我可能想再次加载这些选项(真的是整个表单)来编辑它,并保存更改。
我可以成功地从select组件中读取各种选项:
$("#meet_participants").chosen().val();
但是,如果我想设置多个选项,我会尝试这个测试用例:
HTML code:
<div class="row">
<div class="form-group">
<label class="control-label">Participantes</label><br>
<b>
<select data-placeholder="Ingrese los nombres" class="chosen-select form-control" style="width:60%" multiple id="meet_participants">
<!--Filled with all db users.-->
<option>hola</option>
<option>mundo</option>
<option>cruel</option>
<option>como</option>
<option>estas</option>
</select>
</b>
<button class="btn btn-primary"><b>Tareas pendientes</b></button>
</div> <!--formgroup-->
</div> <!--row-->
之后我做(按照例子)
<!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="js/plugins/jquery-1.11.1.min.js"></script>
<script src="js/plugins/bootstrap.min.js"></script>
<script src="js/plugins/chosen.jquery.js" type="text/javascript"></script>
<script type="text/javascript">
var config = {
'.chosen-select' : {},
'.chosen-select-deselect' : {allow_single_deselect:true},
'.chosen-select-no-single' : {disable_search_threshold:10},
}
for (var selector in config) {
$(selector).chosen(config[selector]);
}
</script>
<script>
fillMemoForm();
$("#meet_participants").chosen().val(["hola", "mundo", "cruel"]);
</script>
只有最后一行很重要,但我粘贴一切以防万一。据我所知,这应该将选定的值设置为这三个项目,但它没有。我做错了什么?
答案 0 :(得分:5)
对此更好的解决方案是
,而不是破坏和重新创建dom元素$('#meet_participants').val(["hola","mundo","cruel"]).trigger('chosen:updated');
答案 1 :(得分:1)
选择的插件中的Val不会刷新控件。调用destroy,取而代之的是
$('#meet_participants').chosen('destroy').val(["hola","mundo","cruel"]).chosen();
$('#meet_participants').chosen();
$('#btn1').click(function() {
$('#meet_participants').chosen('destroy').val(["hola", "mundo", "cruel"]).chosen();
});
$('#btn2').click(function() {
$('#meet_participants').chosen('destroy').val(["estas", "como"]).chosen();
});
body {
padding: .5rem;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://harvesthq.github.io/chosen/chosen.jquery.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet" />
<link href="http://harvesthq.github.io/chosen/chosen.css" rel="stylesheet" />
<form role="form">
<div class="form-group">
<select data-placeholder="Ingrese los nombres" class="chosen-select form-control" multiple id="meet_participants" style="width:50%">
<option>hola</option>
<option>mundo</option>
<option>cruel</option>
<option>como</option>
<option>estas</option>
</select>
</div>
<div class="form-group">
<button id="btn1" class="btn">set ["hola", "mundo", "cruel"]</button>
</div>
<div class="form-group">
<button id="btn2" class="btn">set ["estas", "como"]</button>
</div>
</form>