Brian Anderson Brian Anderson - 1 month ago 4x
Ajax Question

Loading dynamic "chosen" select elements

I am using the jQuery plugin chosen (by Harvest). It is working fine on (document).ready, but I have a button that, when clicked, uses ajax to dynamically create more select objects that I want to use the "chosen" feature. However, only the original select elements have the "chosen" features, and the new (dynamically created) do not work. I am using jQuery.get to append the new elements. Here is a sample of the code:

jQuery(".select").chosen();//this one loads correctly
jQuery("#add-stage").click(function() {
jQuery.get('/myurl',{},function(response) {
//response contains html with 2 more select elements with 'select' class
jQuery(".select").chosen();//this one doesn't seem to do anything :-(

I was thinking that I need a .live() function somewhere, but I haven't been able to figure that out yet. Any help is much appreciated!

Note - I am not trying to dynamically load new options, as specified in the documentation using


Ensure that the response elements have the select class.

console.log( response );  // to verify

May also be a good idea to only apply the plugin to the new element(s).


jQuery("#add-stage").click(function() {
    jQuery.get('/myurl',{},function(response) {
        console.log( response ); // verify the response

        var $response = $(response);  // create the elements

        $response.filter('.select').chosen(); // apply to top level elems
        $response.find('.select').chosen();   // apply to nested elems

Also, if /myurl is returning an entire HTML document, you may get unpredictable results.