Skip to content

Instantly share code, notes, and snippets.

@valsteen
Created December 24, 2014 12:39
Show Gist options
  • Save valsteen/d3669888ed5c37b7ccf9 to your computer and use it in GitHub Desktop.
Save valsteen/d3669888ed5c37b7ccf9 to your computer and use it in GitHub Desktop.
django-autocomplete-light==2.0.3 + jquery.formset.js 1.3-pre
<script src="{% static 'js/jquery.formset.js' %}"></script>
<script>
$(function () {
$('#myformset tbody tr').formset({
'added': function (row) {
var widget = $(".autocomplete-light-widget", row);
widget.yourlabsWidget('destroy');
widget.find('input').yourlabsAutocomplete('destroy');
widget.trigger('initialize');
}
});
});
</script>
@valsteen
Copy link
Author

I'm using crispy forms to render the formset in a table, the formset is made dynamic thanks to https://github.com/elo80ka/django-dynamic-formset , and some input elements use the autocomplete feature from https://github.com/yourlabs/django-autocomplete-light . The problem : as "add another" is used, if I click the newly created input, the autocomplete box appears for the last non-dynamic input.

Solution in this gist : turn it off and on again. The code doesn't need to be customized depending on the type of data, because autocomplete-light just uses available information found in the widget attributes, which is nice. This snippet just needs to be passed to the "added" hook of jquery.formset.

This should be enough, but another hint if you want to use crispyforms to display formsets in a table, I had to patch jquery.formset.js with the following ( it's not an overridable property ) :

// replaces childElementSelector = 'input,select,textarea,label,div',
childElementSelector = 'input,select,textarea,label,div,span,td',

Otherwise some name and ids aren't updated which may cause javascript headaches.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment