Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change the value of Chosen.js select box using jQuery

Tags:

jquery

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

like image 921
Spitz Avatar asked Mar 12 '12 07:03

Spitz


People also ask

How can select option selected using jQuery?

You can select on any attribute and its value by using the attribute selector [attributename=optionalvalue] , so in your case you can select the option and set the selected attribute. $("div. id_100 > select > option[value=" + value + "]"). prop("selected",true);

How do I get the value of a select tag?

To get the value of a select or dropdown in HTML using pure JavaScript, first we get the select tag, in this case by id, and then we get the selected value through the selectedIndex property. The value "en" will be printed on the console (Ctrl + Shift + J to open the console).


2 Answers

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

like image 75
Spitz Avatar answered Sep 22 '22 13:09

Spitz


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');
like image 41
Semyaz Avatar answered Sep 24 '22 13:09

Semyaz