Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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('#stages').append(response);
        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 trigger("liszt:updated");

like image 577
Brian Anderson Avatar asked Dec 01 '11 23:12

Brian Anderson


2 Answers

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(".select").chosen();

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
        $response.appendTo('#stages');
    });
});

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

like image 142
RightSaidFred Avatar answered Nov 04 '22 10:11

RightSaidFred


after you code (fill the select) .write this

$(".select").trigger("chosen:updated");
like image 30
Rober Dote Avatar answered Nov 04 '22 08:11

Rober Dote