Created
December 4, 2014 23:22
-
-
Save cwurld/1b009ccbf013bddefd75 to your computer and use it in GitHub Desktop.
For Fixing Chosen Selects Created by Django Dynamic Formsets
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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