Search code examples
javascriptjqueryajaxjquery-chosen

jQuery Chosen plugin update issue after AJAX call


I'm having an issue with the plugin not applying to a control that is rebuilt by an call. I've looked around at other suggestions but don't seemed to have found a working answer.

I'm using 3.2.1 and 1.8.2

My page is built in and upon first output everything is fine e.g:

<div id="leveldiv">
  <p>
    <label for="fk_level">Level</label>
    <select name="fk_level" class="chosen-select" id="fk_level" title="Level"><option value="0" selected = "selected">None</option>
    </select>
  </p>
</div>

<script type="text/javascript">
  $(".chosen-select").chosen({
    width: "200px"
  });
</script>

During runtime the fk_level select control is rebuilt using an call which calls the same function used to initially draw the control. However the chosen functionality is lost and it just renders as a standard select box.

I've called both the .trigger("liszt:updated") method nd.trigger("chosen:updated") of the select control after replacing the containing div innerHTML but this doesn't seem to have any effect.

AJAX controlling code:

function buildLevel() {
  exID = window.document.forms[0].fk_examtype.value;
  sID = window.document.forms[0].fk_subject.value;

  str = "?action=1&exID=" + exID + "&sID=" + sID

  xmlhttp = getHTTPObject();
  xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("leveldiv").innerHTML = this.responseText;
      $("#fk_level").trigger("liszt:updated");
      $("#fk_level").trigger("chosen:updated");
    }
  };
  xmlhttp.open("GET", "ajax.php" + str, true);
  xmlhttp.send();
}

And just for completeness, an example output from the call is:

<p>
  <label for="fk_level">Level</label>
  <select name="fk_level" id="fk_level" class="chosen-select" title="Level">
    <option value="0">None</option>
  </select>
</p>

I've been fiddling about with this for days now but just cant get the chosen plugin to apply to the control after the call. I've debugged this in Firefox Developer Edition and it's throwing no errors.

Any help would be appreciated.

Mark.


Solution

  • $("#fk_level").trigger("chosen:updated"); works if select box is not destroyed and values are changed. If select box is destroyed and recreated, you need to reactivate the plugin for the new select box. So, in your AJAX controlling code, replace

    $("#fk_level").trigger("liszt:updated");
    $("#fk_level").trigger("chosen:updated");
    

    with

    $("#fk_level").chosen({
        width: "200px"
    });