I'm using Koenpunt's fork of chosen, which allows me to use the "create_option" option in the config object.
It provides a neat way for users to create elements when it's not available in the select box.
Right now it works by making the user click on the 'create new thing' link which appears in the box, but I'd like it to create these new options automatically. Is this possible? Is there an event I should trigger?
As per my understanding,
Chosen.jquery.js
has this ability only by clicking the Add Option link.Let me keep it simple, triggering Add Option link via key event(eg: enter key) will be better. After a long multiple tries I found the opt method from chosen.js
Chosen.prototype.keydown_checker = function(evt){
...
...
}
Add the below script in you html file after intializing the jQuery
and Koenpunt's fork of Chosen.js
<script type="text/javascript">
Chosen.prototype.keydown_checker = function(evt) {
if( event.which === 13) {
$(this.form_field).append('<option>' + $(evt.target).val() + '</option>');
$(this.form_field).trigger('liszt:updated');
this.result_highlight = this.search_results.find('li.active-result').last();
return this.result_select(evt);
}
}
</script>
I'm trying to create a JSFiddle, hope will get it.
EDIT1: Atlast I got it in JSFIDDLE1
EDIT2: While trying to find a way for onBlur()
, I got the following opt method
AbstractChosen.prototype.input_blur = function(evt){
...
...
}
Little change in the above code:
AbstractChosen.prototype.input_blur = function(evt) {
$(this.form_field).append('<option>' + $(evt.target).val() + '</option>');
$(this.form_field).trigger('liszt:updated');
this.result_highlight = this.search_results.find('li.active-result').last();
return this.result_select(evt);
}
Corresponding JSFiddle2 Hope you can find the differences in both the fiddles.
I suggest you take a look at selectize.js, it has the exact functionality that you're looking for (i.e. creating an option on-blur).
Select2 is also another alternative, it also has the same tagging functionality that you expect (see the "Tagging Support" section at the bottom of the demo).
Edit: Added Select2
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