JCB
JCB

Reputation: 167

Change events on dynamically added selects using the Chosen plugin

I'm using the Chosen plugin on my site, and so far it has been working perfectly. However, I'm in a situation where I added a select dynamically and activated the Chosen plugin on those selects. These Chosen selects are being produced fine, but I cannot figure out how to bind a click event to the element. Chosen offers this( $("#form_field").chosen().change( … );) as a way to do something on the change event, however, this does not work since my select was added dynamically.

I have tried $('#el').change and $(document).on("change", "#el", function()) as well without any success.

Upvotes: 1

Views: 1570

Answers (2)

A Mind United
A Mind United

Reputation: 340

Original Answer: From http://harvesthq.github.io/chosen/#change-update-events

"If you need to update the options in your select field and want Chosen to pick up the changes, you'll need to trigger the "chosen:updated" event on the field. Chosen will re-build itself based on the updated content."

$("#form_field").trigger("chosen:updated");

...so just call that after you add the new element.

Edit: After reviewing this http://jsfiddle.net/amindunited/reh5p0tg/3/ I can see that the issue was that the change() listener for the second select was being attached before that select was added to the page. I have updated the fiddle code to work:

http://jsfiddle.net/amindunited/reh5p0tg/4/

Upvotes: 3

Miro
Miro

Reputation: 8650

EDIT

Another way to make it work is to stuff everything inside an init function:

function init_new_content(){
  $("#form_field").chosen();
}
init_new_content();

And then call it whenever you know you made a change (for example on ajax)

$.ajax({...},
            success: function( data){
                     init_new_content();
            },
...

Upvotes: 1

Related Questions