我正在使用
jquery,我想从
javascript设置选定的值
使用Javascript / jQuery的
$(document).ready(function() { var selectedUserRole = document.getElementById('SelectedUserRole').value; var str_array = selectedUserRole.split(','); for (var i = 0; i < str_array.length; i++) { // Trim the excess whitespace. str_array[i] = str_array[i].replace(/^\s*/,"").replace(/\s*$/,""); // Add additional code here,such as: $("UserRole").prop('selectedValue',str_array[i]); // Here not working } });
HTML:
@Html.DropDownList("UserRole",null,new { id = "UserRole",@class = "chosen-select",@multiple = "multiple",@placeholder = "Lütfen Rol Seçiniz",@style = "width: 250px;" })
str_array的值如下
[5,1,7]
我想设置5个值,选择1个值,选择7个值
当我尝试下面
$("UserRole").prop('selectedValue',str_array[i]);
它不适合我.
解决方法
设置选择值后,需要触发所选的:updated事件
$("#UserRole").val(str_array[i]).trigger("chosen:updated");
选择多个值
$(document).ready(function () { var selectedUserRole = document.getElementById('SelectedUserRole').value; var str_array = selectedUserRole.split(','); for (var i = 0; i < str_array.length; i++) { str_array[i] = str_array[i].replace(/^\s*/,""); } $("#UserRole").val(str_array).trigger("chosen:updated"); });
演示:Fiddle