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
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);
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).
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
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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With