I am managing a django website with custom js/widgets that I have created myself. The following is an example of the js code I am using:
$(document).ready(function() {
$(".input_group_text_clear button").on("click", function (e) {
data_action = $(this).attr('data-action');
data_target = $(this).attr('data-target');
$.each(data_target.split(':'), function(i, target) {
$("#" + target).val("").trigger("change");
});
e.preventDefault();
});
});
While this code works well when attached to a django widget and included in the template, I encounter issues when posting forms via ajax. After a failed submission, the form along with any error messages/blocks are returned through a json api. I then replace the original form element with the updated one containing errors.
The problem arises when I need to rebind the controls for them to work as intended. My current approach involves extracting the "binding" code into a global function and calling it from the ajax/done handler. However, this method feels inefficient as it requires assuming which controls are present in the form. Are there any best practices for handling element replacement while binding js functions?
Any help or advice on this matter would be greatly appreciated. Sincerely, Paul