I'm using the chosen.js plugin http://harvesthq.github.com/chosen/ with jQuery to allow the user to select multiple options from a select. However, I now want to be able to let them create values that aren't already present - any idea how to go about this?
EDIT: something similar to SO's own tag selection/creation bar would be close to what I'm after
Preferably without changing or editing the plugin, but will do if required.
The code: HTML:
<p>Select something</p>
<select name="theSelect[]" multiple="multiple">
<option value="First Option">First Option</option>
<option value="Second Option">Second Option</option>
</select>
Javascript:
$(function(){
$('select').chosen();
});
So if a user were to type in "Third Option", i'd like to add that to the list and have it selected. The value and display name are / will be the same so that's not a concern
I tried several solutions given here and elsewhere, however none worked in chosen.js 1.8.5 (jQuery: 3.3.1) and so I ended up with the following since I didn't want to use a fork that might not always be up-to-date to the master branch:
For the case that I might not want any
.chosen-select
to allow new values, I added a new class.chosen-newValuesAllowed
. I set an event handler on this class where CTRL + I adds the new value if it is not yet present. The focus on the input field does not get lost afterwards. In my example, I check the innerHTML of the since @value actually contains database ids and therefore the new value, which is a string in my example that would be processed by the server later, could never be found in @value. If you want to check @value, please see the comment inside the snippet. The code handles single and multiple selects.Another solution would be to call the triggerable function chosen:no_results if new values should only be added if there explicitly is no result:
You could just attach an event to the input text box to listen for a particular character code. After that add the option and trigger the update on the dropdown.
According to the documentation you can try doing something like this:
As Tony stated in the comments below:
"Starting with version 1.0 which the trigger is now "chosen:updated". See harvesthq.github.io/chosen/#change-update-events"
I was just trying to solve the same problem. I wound up modifying the source code a bit. Here's the new keyup_checker function. Take a look at case 13: