Skip to content

Instantly share code, notes, and snippets.

@cwurld
Created December 4, 2014 23:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cwurld/1b009ccbf013bddefd75 to your computer and use it in GitHub Desktop.
Save cwurld/1b009ccbf013bddefd75 to your computer and use it in GitHub Desktop.
For Fixing Chosen Selects Created by Django Dynamic Formsets
/**
* Created by Chuck Martin on 12/4/14.
*
* When django-dynamic-formset creates a new formset and that formset used the "Chosen" widget
* (http://harvesthq.github.io/chosen/), the newly created Chosen widget does not work right.
*
* This code solves that problem by replacing the select (along with the chosen code) that was cloned with a new
* select created from scratch.
*
* This function returns a function for creating a new select that can be associated with Chosen.
* You can use the returned function in your code that is run when a new formset is add.
*
* Note: I tried some other methods that did not work. One was to just update the name and id of the select created
* by django-dynamic-formset. The other was various permutations of this:
* http://stackoverflow.com/questions/10523395/how-to-add-chosen-plugin-to-dynamically-created-cloned-css-div
*
* Inputs:
* container_class: a jquery selector string for the container (e.g. div or table cell) that contains
* the select (eg '.my_select_containers').
* select_class: a jquery selector string for the select (eg '.my_selects').
* options: an array of tuples [[option value, option text], ...] for creating the select.
*
* Return: returns a function that creates a new select that can be associated with Chosen.
*/
var make_fix_chosen_function = function(container_class, select_class, options){
// row is row is the jquery tr object of the new row
return function(row){
// Get the table cell that holds the select and chosen code
var table_cell = $($(row).find(container_class)[0]);
// Get the id and name of the select created by django-dynamic-formset
var the_select = $(row).find(select_class)[0];
// Make the new select from options
var new_select = $("<select id=\"" + the_select.id +
"\" name=\"" + the_select.name +
"\" class=\"" + the_select.className + "\"/>");
$.each(options, function(index){
$("<option />", {value: options[index][0], text: options[index][1]}).appendTo(new_select);
});
table_cell.html(new_select[0]);
// ****NOTE*** the select has not been associated with chosen yet. The reason for this is it makes it possible
// to pass options to chosen.
return new_select;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment