13

I'm trying to change the value of my select box which has Chosen.js overlay. The idea is to change the selected value when user clicks a button.

With regular select box I can change the value by doing:

$('#GroupsShowNext').unbind("click").click(function() {
    var index = $("#GroupsViewGroups").prop("selectedIndex");
    index += 1;

    $('#GroupsViewGroups option').eq(index).attr('selected', 'selected');
    $('#GroupsViewGroups').change();
});

But with Chosen.js it doesn't work anymore..I have tried few things but nothing has worked. Any ideas how to get it work?

Fiddle

Spitz
  • 713
  • 1
  • 9
  • 17
  • possible duplicate of [Changing selection in a select with the Chosen plugin](http://stackoverflow.com/questions/8980131/changing-selection-in-a-select-with-the-chosen-plugin) – Chamika Sandamal Apr 11 '14 at 05:03

4 Answers4

24

So after posting this question I continued trying to solve this problem and happened to found out a way to do this.

$('#GroupsShowNext').unbind("click").click(function() {
    var index = $("#GroupsViewGroups").prop("selectedIndex");
    index += 1;
    $('#GroupsViewGroups option').eq(index).attr('selected', 'selected');
    $('#GroupsViewGroups').chosen().change();
    $("#GroupsViewGroups").trigger("liszt:updated");
});

The key was to put .chosen() before .change() and then trigger "liszt:updated". It works but I don't know if this is the best way to do this..

If you have a better way to do this, please let me know

Spitz
  • 713
  • 1
  • 9
  • 17
8

I stumbled across this trying to figure it out myself.

I was able to do it with a combination of changing the selected index on the original field, and then triggering the liszt:updated event on that field:

$('#GroupsViewGroups')[0].selectedIndex = $('#GroupsViewGroups')[0].selectedIndex + 1;
$('#GroupsViewGroups').trigger('liszt:updated');
Littm
  • 4,923
  • 4
  • 30
  • 38
Semyaz
  • 91
  • 1
  • 3
5

Just an update (I found this page from google, maybe other people will find it also)

I've tryed to comment the @splitz's answer but I couldn't because I still don't have enough reputation.

The new way to do it is:

$('#GroupsShowNext').unbind("click").click(function() {
    var index = $("#GroupsViewGroups").prop("selectedIndex");
    index += 1;
    $('#GroupsViewGroups option').eq(index).attr('selected', 'selected');
    $("#GroupsViewGroups").trigger("chosen:updated");
});

Now, the trick is the "chosen:updated".

Updated answer found on: Changing selection in a select with the Chosen plugin

Community
  • 1
  • 1
2

With the plugin Chosen.js it works.

var myIndex = 4;

$("select#GroupsViewGroups").prop('selectedIndex', myIndex);
Ry-
  • 218,210
  • 55
  • 464
  • 476
Marta
  • 21
  • 2