Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery chosen fails on regenerated content

I am generating the contents on my <select> via ajax. The first time the <option>s load via ajax - all is good and chosen is triggered correctly, even if I had pre-loaded content in that <select>. but if i generate the <option>s a second time - i cannot get chosen to fire.

Here is a jsfiddle to show you what i mean: https://jsfiddle.net/kneidels/vrp0gz1c/

Hit GO the first time - everything is fine. But hit it again, and the select reverts back to the old non-chosen style.

Can someone help me "reset" the plugin so that it fires correctly EACH time?

Using Chosen Version: 1.87

like image 200
kneidels Avatar asked Sep 13 '18 12:09

kneidels


1 Answers

Change your code from:

$("#trigger").click(function(){
    $("#myselect").show().html('<option value="1">1</option><option value="2">2</option><option value="3">3</option><option value="4">4</option>');
    $('#myselect_chosen').remove();
    $("#myselect").chosen({rtl: true, allow_single_deselect: true});    
})

to:

$("#trigger").click(function(){
    let $mySelect = $("#myselect");

  // Make sure previous instantiations have been cleaned-up.
    $mySelect.chosen("destroy");
    $mySelect.html('<option value="1">1</option><option value="2">2</option><option value="3">3</option><option value="4">4</option>');
    $mySelect.chosen({rtl: true, allow_single_deselect: true});
})

You can see this working here i.e. subsequent presses of "Go" now result in the chosen component being rendered correctly.

You didn't need the call to show() (which just displays the element) and your remove statement was invalidating the instantiated chosen object.

like image 184
Ben Smith Avatar answered Oct 21 '22 21:10

Ben Smith