Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing selection in a select with the Chosen plugin

I'm trying to change the currently selected option in a select with the Chosen plugin.

The documentation covers updating the list, and triggering an event when an option is selected, but nothing (that I can see) on externally changing the currently selected value.

I have made a jsFiddle to demonstrate the code and my attempted ways of changing the selection:

$('button').click(function() {     $('select').val(2);     $('select').chosen().val(2);     $('select').chosen().select(2); }); 
like image 292
gak Avatar asked Jan 23 '12 23:01

gak


People also ask

How do I change selected option in select tag?

In order to change the selected option by the value attribute, all we have to do is change the value property of the <select> element. The select box will then update itself to reflect the state of this property. This is the easiest and most straightforward way of updating a select box state.

How to remove chosen jQuery?

By default, pressing delete/backspace on multiple selects will remove a selected choice.

What is jQuery chosen?

Chosen is a JavaScript plugin that makes select boxes user-friendly. It is currently available in both jQuery and Prototype flavors.


1 Answers

From the "Updating Chosen Dynamically" section in the docs: You need to trigger the 'chosen:updated' event on the field

$(document).ready(function() {      $('select').chosen();      $('button').click(function() {         $('select').val(2);         $('select').trigger("chosen:updated");     });  }); 

NOTE: versions prior to 1.0 used the following:

$('select').trigger("liszt:updated"); 
like image 99
Lucas Welper Avatar answered Sep 30 '22 03:09

Lucas Welper