问题
I'm having an issue with the jquery-chosenplugin not applying to a control that is rebuilt by an ajaxcall. I've looked around at other suggestions but don't seemed to have found a working answer.
I'm using jquery3.2.1 and jquery-chosen1.8.2
My htmlpage is built in phpand 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 ajaxcall which calls the same phpfunction 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 ajaxcall 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 ajaxcall. I've debugged this in Firefox Developer Edition and it's throwing no javascripterrors.
Any help would be appreciated.
Mark.
回答1:
$("#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"
});
来源:https://stackoverflow.com/questions/48345818/jquery-chosen-plugin-update-issue-after-ajax-call