Beyto
Beyto

Reputation: 379

Jquery chosen set selected values from javascript

I am using jquery chosen and I want to set selected values from 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 has values below

[5, 1, 7]

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

When I tried below

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

it is not working for me.

Upvotes: 18

Views: 37137

Answers (4)

Claus Lens
Claus Lens

Reputation: 159

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

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

Upvotes: 6

Arun P Johny
Arun P Johny

Reputation: 388316

You need to trigger the chosen:updated event after setting the select value

$("#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

Upvotes: 32

I&#39;m Geeker
I&#39;m Geeker

Reputation: 4637

Use this

You missed '#'

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

Upvotes: 3

Kartikeya Khosla
Kartikeya Khosla

Reputation: 18873

Instead of

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

It should be

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

Upvotes: 2

Related Questions