Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make the "create option" feature onblur in chosen plugin?

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?

like image 674
Aditya M P Avatar asked Jan 14 '23 06:01

Aditya M P


2 Answers

As per my understanding,

  1. You're trying to add options dynamically while typing it in the SearchBox.
  2. Koenpunt's fork of 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.

like image 142
Praveen Avatar answered Feb 15 '23 10:02

Praveen


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

like image 27
Subhas Avatar answered Feb 15 '23 11:02

Subhas