Javascript Jquery从javascript中选择了一组选定的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28691032/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:15:25  来源:igfitidea点击:

Jquery chosen set selected values from javascript

javascriptjquery

提问by Beyto

I am using jquery chosen and I want to set selected values from javascript

我正在使用选择的 jquery,我想从 javascript 设置选定的值

Javascript/Jquery

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 has values below

str_array 具有以下值

[5, 1, 7]

[5, 1, 7]

I want to set 5 value selected, 1 value selected 7 value selected

我想设置选择 5 个值,选择 1 个值 选择 7 个值

When I tried below

当我在下面尝试时

$("UserRole").prop('selectedValue', str_array[i]);

it is not working for me.

它不适合我。

回答by Arun P Johny

You need to trigger the chosen:updatedevent after setting the selectvalue

chosen:updated设置select值后需要触发事件

$("#UserRole").val(str_array[i]).trigger("chosen:updated");


To select multiple values

选择多个值

$(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*/, "").replace(/\s*$/, "");
    }

    $("#UserRole").val(str_array).trigger("chosen:updated");
});

Demo: Fiddle

演示:小提琴

回答by Claus Lens

As of now this way is supported to update multiple values:

截至目前,支持这种方式来更新多个值:

$("#UserRole").val(str_array).trigger("chosen:updated");

回答by Kartikeya Khosla

Instead of

代替

$("UserRole").prop('selectedValue', str_array[i]);

It should be

它应该是

$("#UserRole").prop('selectedValue', str_array[i]); // include '#' id selector here

回答by I'm Geeker

Use this

用这个

You missed '#'

你错过了 '#'

$("#UserRole").prop('selectedValue', str_array[i]);